package org.tgcloud.group.service.app;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.models.auth.In;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.tgcloud.group.core.*;
import org.tgcloud.group.core.date.DateUtils;
import org.tgcloud.group.entity.*;
import org.tgcloud.group.repository.*;
import org.tgcloud.group.service.manager.OrderManagerService;
import org.tgcloud.group.service.manager.notify.NotifyService;
import org.tgcloud.group.service.manager.process.ProcessManageService;
import org.tgcloud.group.service.task.SendSubscribeMsgTask;
import org.tgcloud.group.web.controller.dto.order.*;
import org.tgcloud.group.web.controller.dto.process.ProcessToUser;
import org.tgcloud.group.web.controller.dto.user.NormalUserNameDTO;
import org.tgcloud.group.web.controller.manager.process.enums.ProcessEnum;
import org.tgcloud.group.web.controller.req.order.*;
import org.tgcloud.group.web.controller.req.page.SearchAppPageReq;
import org.tgcloud.group.web.controller.req.project.UpdateProjectOutGoodReq;
import org.tgcloud.group.web.websocket.WebSocketServer;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static org.tgcloud.group.core.BaseLogger.printErrorInfo;

/**
 * @author: zhy
 * @create: 2023-08-16 13:14
 * @description:
 */
@Service
public class OrderService {

    @Autowired
    private MjOrderMapper orderMapper;

    @Autowired
    private MjOrderSendMsgMapper orderSendMsgMapper;

    @Autowired
    private SysLabelValueMapper labelValueMapper;

    @Autowired
    private MjGoodSkuMapper goodSkuMapper;

    @Autowired
    private MjNormalUserMapper normalUserMapper;

    @Autowired
    private SysManagerUserMapper managerUserMapper;

    @Autowired
    private MjUserOrderMapper userOrderMapper;

    @Autowired
    private MjUserOrderGoodMapper userOrderGoodMapper;

    @Autowired
    private SysLabelValueMapper sysLabelValueMapper;

    @Autowired
    private MjOrderBlindBoxMapper orderBlindBoxMapper;

    @Autowired
    private SendSubscribeMsgTask sendSubscribeMsgTask;

    @Autowired
    private MjProjectMapper projectMapper;

    @Autowired
    private MjUserOrderStatusMapper mjUserOrderStatusMapper;

    @Autowired
    private MjUserOrderCheckMapper userOrderCheckMapper;

    @Autowired
    private MjOrderLocalLifeMapper orderLocalLifeMapper;

    @Autowired
    private MjOrderHotelMapper mjOrderHotelMapper;

    @Autowired
    private MjOrderTimeOutRemarkMapper orderTimeOutRemarkMapper;

    @Autowired
    private LogOperateMapper logOperateMapper;

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private DateUtils dateUtils;

    @Autowired
    private MjOrderOtherSettingMapper orderOtherSettingMapper;

    @Autowired
    private MjOrderRateRecordMapper orderRateRecordMapper;

    @Autowired
    private OrderManagerService orderManagerService;

    @Autowired
    private MjProjectStageMapper projectStageMapper;

    @Autowired
    private MjBusinessPersonMapper businessPersonMapper;

    @Autowired
    private ProcessManageService processManageService;

    @Autowired
    private NotifyService notifyService;

    public void doSetOrderList(ManagerOrderDTO dto, Integer userId, Short userType){
        // 倒计时计算
        if (dto.getPushUserHandleDiffTime() != null){
            dto.setPushSureCheckDate(dto.getPushUserHandleDiffTime());
        }else {
            if (dto.getProjectType() == 1){
                // 正常订单，不包含小程序提交的其他订单
                if (dto.getPushSureCheckType() != null){
                    if (dto.getPushSureCheckType() == 1 && dto.getPushTime() != null){
                        Long holidayNumByTime = dateUtils.getHolidayNumByTime(dto.getPushTime().getTime(), new Date().getTime());
                        dto.setPushSureCheckDate(holidayNumByTime);
                    }else if (dto.getPushSureCheckType() == 2 && dto.getPushSureCheckTime() != null){
                        Long holidayNumByTime = dateUtils.getHolidayNumByTime(dto.getPushTime().getTime(), dto.getPushSureCheckTime().getTime());
                        dto.setPushSureCheckDate(holidayNumByTime);
                        orderMapper.updatePushUserHandleDiffTimeById(holidayNumByTime, dto.getId());
                    }
                }
            }
        }
        if (dto.getStatus() != 1){
            List<MjOrderSendMsg> msgs = orderSendMsgMapper.selectListByOrderId(dto.getId(), (short) 1);
            dto.setSendMsgUserList(msgs);
        }
        if (StringUtil.isNotBlank(dto.getCategoryId())){
            String cateName = "";
            for (String id : dto.getCategoryId().split(",")){
                SysLabelValue labelValue = labelValueMapper.selectByPrimaryKey(Integer.valueOf(id));
                cateName = cateName + labelValue.getSysValueName() + ";";
            }
            dto.setCateNames(cateName);
        }
        //列表展示是否放弃订单
        if (userType == 1){
            MjUserOrder abandonFlag = userOrderMapper.selectIsHaveAbandonByOrderIdAndUserId(userId,dto.getId());
            if (abandonFlag != null){
                dto.setIsAbandon((short) 2);
            }
        }
        //列表展示子订单列表
        if (userType == 2){
            // 开拓者或者助理
            if (ObjUtil.isNotNull(dto.getIsHasChild()) && dto.getIsHasChild() == 2){
                List<ManagerOrderDTO> childOrderList = orderMapper.selectAppChildOrderList(userId,dto.getId());
                if (CollUtil.isNotEmpty(childOrderList)){
                    for (ManagerOrderDTO childDTO : childOrderList) {
                        if (StringUtil.isNotBlank(childDTO.getCategoryId())){
                            String cateName = "";
                            for (String id : childDTO.getCategoryId().split(",")){
                                SysLabelValue labelValue = labelValueMapper.selectByPrimaryKey(Integer.valueOf(id));
                                cateName = cateName + labelValue.getSysValueName() + ";";
                            }
                            childDTO.setCateNames(cateName);
                        }
                    }
                    dto.setChildOrderList(childOrderList);
                }
            }
        }
        if (userType == 3){
            // CEO
            if (ObjUtil.isNotNull(dto.getIsHasChild()) && dto.getIsHasChild() == 2){
                List<ManagerOrderDTO> childOrderList = orderMapper.selectAppCEOChildOrderList(userId,dto.getId());
                if (CollUtil.isNotEmpty(childOrderList)){
                    for (ManagerOrderDTO childDTO : childOrderList) {
                        if (StringUtil.isNotBlank(childDTO.getCategoryId())){
                            String cateName = "";
                            for (String id : childDTO.getCategoryId().split(",")){
                                SysLabelValue labelValue = labelValueMapper.selectByPrimaryKey(Integer.valueOf(id));
                                cateName = cateName + labelValue.getSysValueName() + ";";
                            }
                            childDTO.setCateNames(cateName);
                        }
                    }
                    dto.setChildOrderList(childOrderList);
                }
            }
        }
    }

    public APPResultMessage<Object, ManagerOrderDTO> doGetCEOOrderList(Integer userId, SearchAppPageReq req, List<String> statuses) {
        // 查询固定用户下的数据，然后把已中标、已拒绝的状态改为已结束
        String userSearch = "$.user_9.status";
        PageHelper.startPage(req.getPageNum(),req.getPageSize());
        List<ManagerOrderDTO> dtos = orderMapper.selectAppCEOOrderList(req.getKeyword(),req.getArea(),
                req.getCateName(),req.getPermissionUsername(), req.getStatus(),req.getBussinessUsername(),
                req.getStartTime() == null ? null : new Date(req.getStartTime()), req.getEndTime() == null ? null : new Date(req.getEndTime()),
                statuses, userSearch);
        PageInfo<ManagerOrderDTO> tables = new PageInfo<>(dtos);
        for (ManagerOrderDTO dto : tables.getList()){
            // ceo下传入的userType为2
            short userType = 3;
            doSetOrderList(dto, userId, userType);
            if (dto.getProjectType() == 2){
                // 只有在其他项目的情况下，需要把已中标、已拒绝的状态改为已结束
                if (dto.getOrderStatus() == 90 || dto.getOrderStatus() == 99){
                    dto.setOrderStatus(88);
                }
            }
        }
        ResultMessage result = ResultMessage.builder().setList(tables.getList()).setAllPageNumber(tables.getPages()).setCount(tables.getTotal());
        APPResultMessage<Object, ManagerOrderDTO> message = APPResultMessage.getSuccessMessage();
        message.setResult(result);
        return message;
    }

    public APPResultMessage<Object, ManagerOrderDTO> doGetOrderList(Integer userId, SearchAppPageReq req) {
        Integer showUserId = userId;
        MjNormalUser user = normalUserMapper.selectByPrimaryKey(userId);
        Short userType = user.getUserType();
        Integer createUserId = null;
        if (user.getUserType() == 3){
            SysManagerUser managerUser = managerUserMapper.selectMsgByBindUserId(user.getId());
            createUserId = managerUser.getId();
        }
        List<String> statuses = new ArrayList<>();
        if(StringUtil.isNotBlank(req.getStatusList())){
            String[] split = req.getStatusList().split(",");
            statuses.addAll(Arrays.asList(split));
        }
        if (user.getUserType() != null && user.getUserType() == 4){
            // 提供查看全部功能
            showUserId = null;
            userType = (short) 2;
            // 如果用户是ceo角色，那么需要特殊处理
            return doGetCEOOrderList(userId, req, statuses);
        }
        String userSearch = "$.user_" + userId;
        if (userType == 1){
            userSearch = userSearch + ".status";
        }
        if (req.getPageNum() != null && req.getPageSize() != null){
            PageHelper.startPage(req.getPageNum(),req.getPageSize());
            List<ManagerOrderDTO> dtos = orderMapper.selectAppOrderList(showUserId,userType,createUserId,req.getKeyword(),req.getArea(),
                    req.getCateName(),req.getPermissionUsername(), req.getStatus(),req.getBussinessUsername(),
                    req.getStartTime() == null ? null : new Date(req.getStartTime()), req.getEndTime() == null ? null : new Date(req.getEndTime()),
                    statuses, userSearch);
            PageInfo<ManagerOrderDTO> tables = new PageInfo<>(dtos);
            for (ManagerOrderDTO dto : tables.getList()){
                doSetOrderList(dto, userId, userType);
            }
            ResultMessage result = ResultMessage.builder().setList(tables.getList()).setAllPageNumber(tables.getPages()).setCount(tables.getTotal());
            APPResultMessage<Object, ManagerOrderDTO> message = APPResultMessage.getSuccessMessage();
            message.setResult(result);
            return message;
        } else {
            List<ManagerOrderDTO> dtos = orderMapper.selectAppOrderList(showUserId,userType,createUserId,req.getKeyword(),req.getArea(),
                    req.getCateName(),req.getPermissionUsername(), req.getStatus(),req.getBussinessUsername(),
                    req.getStartTime() == null ? null : new Date(req.getStartTime()), req.getEndTime() == null ? null : new Date(req.getEndTime()),
                    statuses, userSearch);
            for (ManagerOrderDTO dto : dtos){
                // 倒计时计算
                if (dto.getPushUserHandleDiffTime() != null){
                    dto.setPushSureCheckDate(dto.getPushUserHandleDiffTime());
                }else {
                    if (dto.getProjectType() == 1){
                        // 正常订单，不包含小程序提交的其他订单
                        if (dto.getPushSureCheckType() != null){
                            if (dto.getPushSureCheckType() == 1 && dto.getPushTime() != null){
                                Long holidayNumByTime = dateUtils.getHolidayNumByTime(dto.getPushTime().getTime(), new Date().getTime());
                                dto.setPushSureCheckDate(holidayNumByTime);
                            }else if (dto.getPushSureCheckType() == 2 && dto.getPushSureCheckTime() != null){
                                Long holidayNumByTime = dateUtils.getHolidayNumByTime(dto.getPushTime().getTime(), dto.getPushSureCheckTime().getTime());
                                dto.setPushSureCheckDate(holidayNumByTime);
                                orderMapper.updatePushUserHandleDiffTimeById(holidayNumByTime, dto.getId());
                            }
                        }
                    }
                }
//                String readStatus = RedisUtil.getCacheObject("readOrder_" + dto.getId());
//                dto.setRead(true);
//                if (user.getUserType() != 4){
//                    if (StringUtil.isNotBlank(readStatus) && readStatus.indexOf(user.getUserType().toString()) > -1){
//                        dto.setRead(false);
//                    }
//                }
                if (dto.getStatus() != 1){
                    List<MjOrderSendMsg> msgs = orderSendMsgMapper.selectListByOrderId(dto.getId(), (short) 1);
                    dto.setSendMsgUserList(msgs);
                }
                if (StringUtil.isNotBlank(dto.getCategoryId())){
                    String cateName = "";
                    for (String id : dto.getCategoryId().split(",")){
                        SysLabelValue labelValue = labelValueMapper.selectByPrimaryKey(Integer.valueOf(id));
                        cateName = cateName + labelValue.getSysValueName() + ";";
                    }
                    dto.setCateNames(cateName);
                }
                //列表展示是否放弃订单
                if (userType == 1){
                    MjUserOrder abandonFlag = userOrderMapper.selectIsHaveAbandonByOrderIdAndUserId(userId,dto.getId());
                    if (abandonFlag != null){
                        dto.setIsAbandon((short) 2);
                    }
                }
                //列表展示子订单列表
                if (userType == 2){
                    if (ObjUtil.isNotNull(dto.getIsHasChild()) && dto.getIsHasChild() == 2){
                        List<ManagerOrderDTO> childOrderList = orderMapper.selectAppChildOrderList(userId,dto.getId());
                        if (CollUtil.isNotEmpty(childOrderList)){
                            for (ManagerOrderDTO childDTO : childOrderList) {
//                                String readStatus2 = RedisUtil.getCacheObject("readOrder_" + childDTO.getId());
//                                childDTO.setRead(true);
//                                if (user.getUserType() != 4){
//                                    if (StringUtil.isNotBlank(readStatus2) && readStatus2.indexOf(user.getUserType().toString()) > -1){
//                                        childDTO.setRead(false);
//                                    }
//                                }
                                if (StringUtil.isNotBlank(childDTO.getCategoryId())){
                                    String cateName = "";
                                    for (String id : childDTO.getCategoryId().split(",")){
                                        SysLabelValue labelValue = labelValueMapper.selectByPrimaryKey(Integer.valueOf(id));
                                        cateName = cateName + labelValue.getSysValueName() + ";";
                                    }
                                    childDTO.setCateNames(cateName);
                                }
                            }
                            dto.setChildOrderList(childOrderList);
                        }
                    }
                }
            }
            ResultMessage resultMessage = ResultMessage.builder().setList(dtos);
            APPResultMessage<Object, ManagerOrderDTO> successMessage = APPResultMessage.getSuccessMessage();
            successMessage.setResult(resultMessage);
            return successMessage;
        }
    }

    public APPResultMessage<Object, List> doCheckChannelMsg(int userId, CheckChannelUserDTO req) {
//        RedisUtil.setCacheObject("readOrder_" + req.getOrderId(), GlobalStatic.noRead1);
        String userIds = req.getUserIds();
        List<MjOrderSendMsg> msgs = new ArrayList<>();
        for (String id : userIds.split(",")){
            MjOrderSendMsg orderSendMsg = new MjOrderSendMsg();
            orderSendMsg.setOrderId(req.getOrderId());
            orderSendMsg.setMsgType((short) 1);
            orderSendMsg.setMsgStatus((short) 1);
            orderSendMsg.setUserId(Integer.valueOf(id));
            msgs.add(orderSendMsg);
        }
        orderSendMsgMapper.insertBatch(msgs);

        //渠道为待核价
        for (String pushUserId : userIds.trim().split(",")) {
            MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(Integer.valueOf(pushUserId), req.getOrderId());
            if (isHaveObj != null){
                MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                orderStatusObj.setUpdateTime(new Date());
                orderStatusObj.setOrderStatus(71);
                orderStatusObj.setId(isHaveObj.getId());
                mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
            } else {
                MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                orderStatusObj.setUserId(Integer.valueOf(pushUserId));
                orderStatusObj.setOrderId(req.getOrderId());
                orderStatusObj.setOrderStatus(71);
                orderStatusObj.setStatus((short) 1);
                orderStatusObj.setCreateTime(new Date());
                orderStatusObj.setIsNextPush((short) 1);
                mjUserOrderStatusMapper.insertSelective(orderStatusObj);
            }
        }
        //推送的同时开拓者的状态为已分配
        //转移前的开拓者保持转移前的订单状态，直到确认签单后，开始设置一次竞价截止时间
        MjOrder order = orderMapper.selectByPrimaryKey(req.getOrderId());
        MjNormalUser normalUser = normalUserMapper.selectByPrimaryKey(userId);

        if (normalUser.getIsAssistant() != null && normalUser.getIsAssistant() == 2){
            //如果分配的操作者是助理
            //先修改助理的状态
            MjUserOrderStatus orderStatusObj2 = new MjUserOrderStatus();
            orderStatusObj2.setOrderStatus(80);
            orderStatusObj2.setUpdateTime(new Date());
            MjUserOrderStatus isHaveObj2 = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(userId, req.getOrderId());
            //如果是等待签单状态，则不进行修改
            if (isHaveObj2 != null && isHaveObj2.getOrderStatus() != 82){
                orderStatusObj2.setId(isHaveObj2.getId());
                mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj2);
            }
            //渠道所属的开拓者的状态
            List<Integer> pushUserIdList = normalUserMapper.selectPushUserIdByIds(userIds.trim().split(","));
            if (pushUserIdList != null && pushUserIdList.size()>0){
                for (Integer pushUserId : pushUserIdList) {
                    //开拓者
                    MjUserOrderStatus orderStatusObj3 = new MjUserOrderStatus();
                    orderStatusObj3.setOrderStatus(80);
                    orderStatusObj3.setUpdateTime(new Date());
                    MjUserOrderStatus isHaveObj3 = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(pushUserId, req.getOrderId());
                    //如果是等待签单状态，则不进行修改
                    if (isHaveObj3 != null && isHaveObj3.getOrderStatus() != 82){
                        orderStatusObj3.setId(isHaveObj3.getId());
                        mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj3);
                    }
                    //助理---判断是否为上一个状态--加一个sql修改助理userid,orderid,上一步的状态，和要修改的状态
                    List<MjNormalUser> assistantsList = normalUserMapper.selectAssistantsById(pushUserId);
                    if (assistantsList != null && assistantsList.size() > 0){
                        for (MjNormalUser assistantObj : assistantsList) {
                            mjUserOrderStatusMapper.updateAssistant(assistantObj.getId(), req.getOrderId(), 79,80);
                        }
                    }
                }
            }
        } else {
            //如果操作的人是开拓者
            //开拓者
            MjUserOrderStatus orderStatusObj2 = new MjUserOrderStatus();
            orderStatusObj2.setOrderStatus(80);
            orderStatusObj2.setUpdateTime(new Date());
            MjUserOrderStatus isHaveObj2 = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(userId, req.getOrderId());
            //如果是等待签单状态，则不进行修改
            if (isHaveObj2 != null && isHaveObj2.getOrderStatus() != 82){
                orderStatusObj2.setId(isHaveObj2.getId());
                mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj2);
            }
            //助理---判断是否为上一个状态--加一个sql修改助理userid,orderid,上一步的状态，和要修改的状态
            List<MjNormalUser> assistantsList = normalUserMapper.selectAssistantsById(userId);
            if (assistantsList != null && assistantsList.size() > 0){
                for (MjNormalUser assistantObj : assistantsList) {
                    mjUserOrderStatusMapper.updateAssistant(assistantObj.getId(), req.getOrderId(), 79,80);
                }
            }
        }


        String pushUserIds = order.getPushChannelUserIds();
        if (StringUtil.isNotBlank(pushUserIds)){
            pushUserIds = pushUserIds + "," + req.getUserIds();
        }else {
            pushUserIds = req.getUserIds();
        }
        String distinctUserIds = Arrays.stream(pushUserIds.split(","))
                .distinct()
                .collect(Collectors.joining(","));
        orderMapper.updateChannelUserIdsByOrderId(req.getOrderId(),distinctUserIds);
        if (order.getStatus() <= 2){
            orderMapper.updateStatusByOrderId(req.getOrderId(), (short) 2);
        }
        // TODO: 2023/8/31 0031 开拓者推送给渠道，开始核价流程
        sendSubscribeMsgTask.doPushMap(order.getPushChannelUserIds(), order.getOrderKey(), order.getBrands(), "待核价", "请进行核价", null);
        //项目状态改为 核价中-已分配未反馈
        projectMapper.updateStatusById(order.getProjectId(), (short) 6);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage<ManagerOrderDTO, List> getOrderMsg(int userId, OrderIdReq req) {
//        RedisUtil.deleteObject("readOrder_" + req.getOrderId());
        MjNormalUser user = normalUserMapper.selectByPrimaryKey(userId);
        ManagerOrderDTO dto = orderMapper.selectMsgByOrderId(req.getOrderId());

        if (dto.getStatus() != 1){
            List<MjOrderSendMsg> msgs = orderSendMsgMapper.selectListByOrderId(dto.getId(), (short) 1);
            dto.setSendMsgUserList(msgs);
        }
        if (StringUtil.isNotBlank(dto.getCategoryId())){
            String cateName = "";
            for (String id : dto.getCategoryId().split(",")){
                SysLabelValue labelValue = labelValueMapper.selectByPrimaryKey(Integer.valueOf(id));
                cateName = cateName + labelValue.getSysValueName() + ";";
            }
            dto.setCateNames(cateName);
        }
        //订单分类
        if (dto.getFileType() != null){
            if (dto.getFileType() == 1  || dto.getFileType() == 4){
                List<GoodListDTO> goodListDTOS = goodSkuMapper.selectListByOrderId(dto.getId());
                dto.setGoodList(goodListDTOS);
            } else if (dto.getFileType() == 2){
                List<MjOrderLocalLife> goodListDTOS = orderLocalLifeMapper.selectListByOrderId(dto.getId());
                dto.setGoodList(goodListDTOS);
            } else if (dto.getFileType() == 3){
                List<MjOrderHotel> goodListDTOS = mjOrderHotelMapper.selectListByOrderId(dto.getId());
                dto.setGoodList(goodListDTOS);
            }
        }

        String v4 = sysLabelValueMapper.selectValueBySysIdAndReadOne(4);
        dto.setBiddingPoint(v4);
        String v5 = sysLabelValueMapper.selectValueBySysIdAndReadOne(5);
        dto.setBiddingPrice(v5);

        dto.setIsSubmitCheckPrice(true);
        dto.setIsSubmitBiddingFirst(false);
        dto.setIsSubmitBiddingSecond(false);


        if (user.getUserType() == 1){
            // 查询该项目下是否有其他状态的订单，已删除的除外
            List<OtherOrderListDTO> otherOrderListDTOS = orderMapper.selectOtherOrderByProjectIdAndChannelUserId(dto.getProjectId(), dto.getId(), user.getId());
            if (!BeanUtil.isNullList(otherOrderListDTOS)){
                dto.setOtherOrderList(otherOrderListDTOS);
            }

            dto.setIsSubmitCheckPrice(true);
            if (dto.getFileType() != 1){
                dto.setIsSubmitCheckPrice(false);
            }
            MjUserOrder userOrder = userOrderMapper.selectIsHaveByOrderIdAndUserIdAndOrderType(userId, req.getOrderId(), (short) 1);

            if (userOrder != null){
                if (userOrder.getUserId() == userId){
                    dto.setIsSubmitCheckPrice(false);
                    List<ChannelGoodPriceList> goodPriceLists = userOrderGoodMapper.selectListByUserOrderId(userOrder.getId());
                    dto.setGoodPriceLists(goodPriceLists);
                }else {
                    dto.setIsSubmitCheckPrice(true);
                }
            }
            MjUserOrder userOrderBiddingFirst = userOrderMapper.selectIsHaveByOrderIdAndUserIdAndOrderType(userId, req.getOrderId(), (short) 2);
            if (userOrderBiddingFirst != null ){
                dto.setIsSubmitBiddingFirst(true);
                dto.setBiddingFirstPrice(userOrderBiddingFirst.getTotalPrice());
                dto.setChannelFirstStatus(userOrderBiddingFirst.getStatus());
                //一次竞价人数
                Integer firstPersonNum = userOrderMapper.selectNumByOrderIdAndOrderType(req.getOrderId(), (short) 2);

                //控制渠道显示的报价人数，如果>=4，则人数显示4
                if (firstPersonNum != null && firstPersonNum > 3 ){
                    dto.setChannelFirstPersonNum(4);
                } else {
                    dto.setChannelFirstPersonNum(firstPersonNum);
                }
                if (userOrderBiddingFirst.getRankNum() != null){
                    //如果排名在3之后，显示4
                    if (userOrderBiddingFirst.getRankNum() > 3){
                        dto.setChannelFirstRank(4);
                    } else {
                        dto.setChannelFirstRank(userOrderBiddingFirst.getRankNum());
                    }
                }
            }
            MjUserOrder userOrderBiddingSecond = userOrderMapper.selectIsHaveByOrderIdAndUserIdAndOrderType(userId, req.getOrderId(), (short) 3);
            if (userOrderBiddingSecond != null ){
                dto.setIsSubmitBiddingSecond(true);
                dto.setChannelSecondRank(userOrderBiddingSecond.getRankNum());
                dto.setBiddingSecondPrice(userOrderBiddingSecond.getTotalPrice());
                //二次竞价人数
                Integer secondPersonNum = userOrderMapper.selectNumByOrderIdAndOrderType(req.getOrderId(), (short) 3);
                //控制渠道显示的报价人数，如果>=4，则人数显示4
                if (secondPersonNum != null &&  secondPersonNum > 3 ){
                    dto.setChannelSecondPersonNum(4);
                } else {
                    dto.setChannelSecondPersonNum(secondPersonNum);
                }
                dto.setChannelSecondRank(null);
                if (userOrderBiddingSecond.getRankNum() != null){
                    //如果排名在3之后，显示4
                    if (userOrderBiddingSecond.getRankNum() > 3){
                        dto.setChannelSecondRank(4);
                    } else {
                        dto.setChannelSecondRank(userOrderBiddingSecond.getRankNum());
                    }
                }
            }
            //渠道是否已放弃该订单
            MjUserOrder abandonFlag = userOrderMapper.selectIsHaveAbandonByOrderIdAndUserId(userId, req.getOrderId());
            if (abandonFlag != null){
                dto.setIsAbandon((short) 2);
            }
        }else if (user.getUserType() == 2){
            // 开拓者或者助理
            // 查询该项目下是否有其他状态的订单，已删除的除外

            List<OtherOrderListDTO> otherOrderListDTOS = orderMapper.selectOtherOrderByProjectId(dto.getProjectId(), dto.getId(),dto.getParentId());
            if (!BeanUtil.isNullList(otherOrderListDTOS)){
                dto.setOtherOrderList(otherOrderListDTOS);
            }

            List<ChannelUserGoodListDTO> channelUserGoodListDTOS = new ArrayList<>();
            if (dto.getStatus() > 1){
                channelUserGoodListDTOS = userOrderMapper.selectListByOrderIdAndOrderType(req.getOrderId(), (short) 1, userId);
                for (ChannelUserGoodListDTO goodListDTO : channelUserGoodListDTOS){
                    List<ChannelGoodPriceList> goodPriceLists = userOrderGoodMapper.selectListByUserOrderId(goodListDTO.getUserOrderId());
                    goodListDTO.setGoodPriceLists(goodPriceLists);
                }

                dto.setChannelUserGoodListDTOS(channelUserGoodListDTOS);
                if (dto.getStatus() >= 4 && dto.getBiddingOneEndTime() != null){
                    if (user.getIsAssistant() != null && user.getIsAssistant() == 2){
                        //拿到助理所属的开拓者
                        if (StringUtil.isNotBlank(user.getAssistantUserIds())) {
                            //找到开拓者所有渠道
                            List<Integer> userIdList = new ArrayList<>();
                            for (String userIds : user.getAssistantUserIds().split(",")) {
                                List<MjNormalUser> mjNormalUsers = normalUserMapper.selectChannelListByUserId(Integer.parseInt(userIds));
                                for (MjNormalUser mjNormalUser : mjNormalUsers) {
                                    userIdList.add(mjNormalUser.getId());
                                }
                            }
                            //找到userorder存在的渠道
                            List<MjUserOrder> mjUserOrders = userOrderMapper.selectUserList(userIdList,req.getOrderId(),(short) 2);
                            dto.setChannelUserFirstBiddingListAssistant(mjUserOrders);
                        }
                    }
                    else {
                        List<ChannelUserGoodListDTO> channelUserFirstBiddingListDTOS = userOrderMapper.selectListByOrderIdAndOrderType(req.getOrderId(), (short) 2, userId);
                        dto.setChannelUserFirstBiddingListDTOS(channelUserFirstBiddingListDTOS);
                    }
                }
                if (dto.getStatus() >= 5 ){
                    if (user.getIsAssistant() != null && user.getIsAssistant() == 2){
                        //拿到助理所属的开拓者
                        if (StringUtil.isNotBlank(user.getAssistantUserIds())) {
                            //找到开拓者所有渠道
                            List<Integer> userIdList = new ArrayList<>();
                            for (String userIds : user.getAssistantUserIds().split(",")) {
                                List<MjNormalUser> mjNormalUsers = normalUserMapper.selectChannelListByUserId(Integer.parseInt(userIds));
                                for (MjNormalUser mjNormalUser : mjNormalUsers) {
                                    userIdList.add(mjNormalUser.getId());
                                }
                            }
                            //找到userorder存在的渠道
                            List<MjUserOrder> mjUserOrders = userOrderMapper.selectUserList(userIdList,req.getOrderId(),(short) 3);
                            dto.setChannelUserSecondBiddingListAssistant(mjUserOrders);
                        }
                    }
                    else {
                        List<ChannelUserGoodListDTO> channelUserSecondBiddingListDTOS = userOrderMapper.selectListByOrderIdAndOrderType(req.getOrderId(), (short) 3, userId);
                        dto.setChannelUserSecondBiddingListDTOS(channelUserSecondBiddingListDTOS);
                        List<ChannelUserGoodListDTO> channelUserGoodListDTOS1 = userOrderMapper.selectChallengerList(req.getOrderId(), (short) 3);
                        for (ChannelUserGoodListDTO channelUserGoodListDTO : channelUserGoodListDTOS1) {
                            if (channelUserGoodListDTO.getRankNum() != null && channelUserGoodListDTO.getRankNum() == 1){
                                channelUserSecondBiddingListDTOS.remove(channelUserGoodListDTO);
                            }
                        }
                        dto.setChallengerListDTOS(channelUserGoodListDTOS1);
                    }
                }
            }
            // 获取各自开拓者的渠道商列表
            List<MjNormalUser> mjNormalUsers = normalUserMapper.selectChannelListByUserId(userId);
            Map map = new HashMap();
            for (MjNormalUser normalUser : mjNormalUsers){
                map.put(normalUser.getId(), normalUser.getNickName());
            }
            dto.setChannelUserIds(map);

            // 获取转移前提交的核价表单
            if (dto.getIsNextPush() != null && dto.getIsNextPush() == 2){
                List<ChannelUserGoodListDTO> channelUserHasNextPushBiddingListDTOS = userOrderMapper.selectListByOrderIdAndOrderTypeAndChannelUserIds(req.getOrderId(),(short) 1, dto.getPushUserIds().split(","));
                dto.setNextPushBeforeChannelUserList(channelUserHasNextPushBiddingListDTOS);
            }

            //设置核价信息列表，开拓者和助理可以看到自己的反馈信息
            List<MjUserOrderCheck> userOrderCheckList = userOrderCheckMapper.selectListByUserIdAndOrderId(userId, req.getOrderId(),null);
            if (userOrderCheckList != null && userOrderCheckList.size() > 0){
                dto.setCheckMsgList(userOrderCheckList);
            }

            if (user.getIsAssistant() != null && user.getIsAssistant() == 2){

            } else {
                //开拓者可以看到助理的反馈信息---根据反馈的渠道判断
                List<MjUserOrderCheck> assistantCheckList = userOrderCheckMapper.selectAssistantCheckList(userId,req.getOrderId());
                dto.setAssistantCheckList(assistantCheckList);
            }

            //订单结束，助理可以看到中标渠道的价格
            if (dto.getStatus() > 3 && dto.getLastUserId() != null) {
                NormalUserNameDTO mjNormalUser = normalUserMapper.selectPushNameByChannelId(dto.getLastUserId());
                if (mjNormalUser != null) {
                    dto.setLastChannelName(mjNormalUser.getNickName());
                    dto.setLastPioneerName(mjNormalUser.getPushName());
                    if (userId == mjNormalUser.getPushUserId()){
                        dto.setIsLastPioneer(2);
                    }
                    if (dto.getBiddingTwoTopPrice() != null) {
                        dto.setLastPrice(dto.getBiddingTwoTopPrice());
                    } else if (dto.getBiddingOneFirstPrice() != null) {
                        dto.setLastPrice(dto.getBiddingOneFirstPrice());
                    } else {

                    }
                }
            }

            //设置拒绝报价的渠道名称
            if (StringUtil.isNotBlank(dto.getChannelRefuseIds())){
                List<String> nameList = new ArrayList<>();
                for (String userID : dto.getChannelRefuseIds().split(",")) {
                    MjNormalUser mjNormalUser = normalUserMapper.selectByPrimaryKey(Integer.valueOf(userID));
                    nameList.add(mjNormalUser.getNickName());
                }
                dto.setChannelRefuserNames(nameList);
            }

            //返回商务提交的超时说明
            List<MjOrderTimeOutRemark> remarks = orderTimeOutRemarkMapper.selectByUserIdAndOrderId(null, req.getOrderId(),(short) 1);
            if (remarks != null && !remarks.isEmpty()){
                dto.setBusinessRemark(remarks);
            }

            //返回商开拓者、助理对超时的反馈意见
            List<MjOrderTimeOutRemark> remarks2 = orderTimeOutRemarkMapper.selectNormalUserByOrderId(null, req.getOrderId(),(short)2);
            if (remarks2 != null && !remarks2.isEmpty()){
                dto.setBusinessRemarkReply(remarks2);
            }

            //开拓者查看原表单
            if (ObjUtil.isNotNull(dto.getParentId())){
                List<ParentOrderDTO> parentOrderList = orderMapper.selectParentOrderList(dto.getParentId());
                if (CollUtil.isNotEmpty(parentOrderList)){
                    dto.setParentOrderList(parentOrderList);
                }
            }

            // 开拓者查看转移信息，查询转移转推的开拓者
            if (dto.getIsNextPush() != null && dto.getIsNextPush() == 2 &&  StringUtil.isNotBlank(dto.getNextPushUserIds())){
                String s = StringUtil.removeDuplicates(dto.getNextPushUserIds().split(","));
                String[] split = s.split(",");
                List<String> nextPushNames = new ArrayList<>();
                List<String> nextPushAssistants = new ArrayList<>();
                for (String nextPushUserId : split) {
                    MjNormalUser mjNormalUser = normalUserMapper.selectByPrimaryKey(Integer.valueOf(nextPushUserId));
                    // 检查查询结果是否有效
                    if (mjNormalUser != null) {
                        //判断是否助理
                        if (mjNormalUser.getIsAssistant() == (short)1){
                            nextPushNames.add(mjNormalUser.getNickName());
                        } else if(mjNormalUser.getIsAssistant() == (short)2){
                            nextPushAssistants.add(mjNormalUser.getNickName());
                        }
                    }
                }
                dto.setNextPushUserNames(nextPushNames);
                dto.setNextPushAssistantNames(nextPushAssistants);
            }
            //查询推送的人
            if (StringUtil.isNotBlank(dto.getPushUserIds())){
                StringBuilder userNamesBuilder = new StringBuilder();
                StringBuilder assistantNamesBuilder = new StringBuilder();
                String s = StringUtil.removeDuplicates(dto.getPushUserIds().split(","));
                for (String pushUserId : s.trim().split(",")) {
                    MjNormalUser mjNormalUser = normalUserMapper.selectByPrimaryKey(Integer.valueOf(pushUserId));
                    // 检查查询结果是否有效
                    if (mjNormalUser != null) {
                        //判断是否助理
                        if (mjNormalUser.getIsAssistant() == (short)1){
                            if (userNamesBuilder.length() > 0) {
                                userNamesBuilder.append(",");
                            }
                            userNamesBuilder.append(mjNormalUser.getNickName());
                        } else if(mjNormalUser.getIsAssistant() == (short)2){
                            if (assistantNamesBuilder.length() > 0) {
                                assistantNamesBuilder.append(",");
                            }
                            assistantNamesBuilder.append(mjNormalUser.getNickName());
                        }
                    }
                }
                dto.setPushUserName(userNamesBuilder.toString());
                dto.setPushAssistantName(assistantNamesBuilder.toString());
            }


            // 评级
            if (dto.getRateId() != null){
                OrderRateDTO rateDTO = orderManagerService.doGetRateContent(dto.getRateId());
                dto.setRate(rateDTO.getRate());
                dto.setRateContent(rateDTO.getAppContent());
            }

        }else if (user.getUserType() == 4){
            // CEO
            // 查询该项目下是否有其他状态的订单，已删除的除外

            List<OtherOrderListDTO> otherOrderListDTOS = orderMapper.selectOtherOrderByProjectId(dto.getProjectId(), dto.getId(),dto.getParentId());
            if (!BeanUtil.isNullList(otherOrderListDTOS)){
                dto.setOtherOrderList(otherOrderListDTOS);
            }
            List<Integer> userList = new ArrayList<>(Arrays.asList(9, 16, 17)); // 开拓者集合

            List<ChannelUserGoodListDTO> channelUserGoodListDTOS = new ArrayList<>();
            if (dto.getStatus() > 1){
                for (Integer pushUserId : userList){
                    channelUserGoodListDTOS = userOrderMapper.selectListByOrderIdAndOrderType(req.getOrderId(), (short) 1, pushUserId);
                    for (ChannelUserGoodListDTO goodListDTO : channelUserGoodListDTOS){
                        List<ChannelGoodPriceList> goodPriceLists = userOrderGoodMapper.selectListByUserOrderId(goodListDTO.getUserOrderId());
                        goodListDTO.setGoodPriceLists(goodPriceLists);
                    }
                }
                dto.setChannelUserGoodListDTOS(channelUserGoodListDTOS);
                if (dto.getStatus() >= 4 && dto.getBiddingOneEndTime() != null){
                    List<ChannelUserGoodListDTO> channelUserFirstBiddingListDTOS = new ArrayList<>();
                    for (Integer pushUserId : userList){
                        List<ChannelUserGoodListDTO> channelUserFirstBiddingListDTOSItem = userOrderMapper.selectListByOrderIdAndOrderType(req.getOrderId(), (short) 2, pushUserId);
                        channelUserFirstBiddingListDTOS.addAll(channelUserFirstBiddingListDTOSItem);
                    }
                    dto.setChannelUserFirstBiddingListDTOS(channelUserFirstBiddingListDTOS);
                }
                if (dto.getStatus() >= 5 ){
                    {
                        List<ChannelUserGoodListDTO> channelUserSecondBiddingListDTOS = new ArrayList<>();
                        List<ChannelUserGoodListDTO> channelUserGoodListDTOS1 = new ArrayList<>();
                        for (Integer pushUserId : userList){
                            List<ChannelUserGoodListDTO> channelUserSecondBiddingListDTOSItem = userOrderMapper.selectListByOrderIdAndOrderType(req.getOrderId(), (short) 3, pushUserId);
                            channelUserSecondBiddingListDTOS.addAll(channelUserSecondBiddingListDTOSItem);
                        }
                        List<ChannelUserGoodListDTO> channelUserGoodListDTOS1Item = userOrderMapper.selectChallengerList(req.getOrderId(), (short) 3);
                        for (ChannelUserGoodListDTO channelUserGoodListDTO : channelUserGoodListDTOS1Item) {
                            if (channelUserGoodListDTO.getRankNum() != null && channelUserGoodListDTO.getRankNum() == 1){
                                channelUserSecondBiddingListDTOS.remove(channelUserGoodListDTO);
                            }
                        }
                        dto.setChannelUserSecondBiddingListDTOS(channelUserSecondBiddingListDTOS);
                        dto.setChallengerListDTOS(channelUserGoodListDTOS1);
                    }
                }
            }
            // 获取各自开拓者的渠道商列表
            Map map = new HashMap();
            for (Integer pushUserId : userList){
                List<MjNormalUser> mjNormalUsers = normalUserMapper.selectChannelListByUserId(pushUserId);
                for (MjNormalUser normalUser : mjNormalUsers){
                    map.put(normalUser.getId(), normalUser.getNickName());
                }
            }
            dto.setChannelUserIds(map);

            // 获取转移前提交的核价表单
            if (dto.getIsNextPush() != null && dto.getIsNextPush() == 2){
                List<ChannelUserGoodListDTO> channelUserHasNextPushBiddingListDTOS = userOrderMapper.selectListByOrderIdAndOrderTypeAndChannelUserIds(req.getOrderId(),(short) 1, dto.getPushUserIds().split(","));
                dto.setNextPushBeforeChannelUserList(channelUserHasNextPushBiddingListDTOS);
            }

            //设置核价信息列表，开拓者和助理可以看到自己的反馈信息
            List<MjUserOrderCheck> userOrderCheckList = new ArrayList<>();
            for (Integer pushUserId : userList){
                List<MjUserOrderCheck> userOrderCheckListItem = userOrderCheckMapper.selectListByUserIdAndOrderId(pushUserId, req.getOrderId(),null);
                if (userOrderCheckListItem != null && userOrderCheckListItem.size() > 0){
                    userOrderCheckList.addAll(userOrderCheckListItem);
                }
            }
            if (userOrderCheckList != null && userOrderCheckList.size() > 0){
                dto.setCheckMsgList(userOrderCheckList);
            }


            //订单结束，助理可以看到中标渠道的价格
            if (dto.getStatus() > 3 && dto.getLastUserId() != null) {
                NormalUserNameDTO mjNormalUser = normalUserMapper.selectPushNameByChannelId(dto.getLastUserId());
                if (mjNormalUser != null) {
                    dto.setLastChannelName(mjNormalUser.getNickName());
                    dto.setLastPioneerName(mjNormalUser.getPushName());
                    if (userId == mjNormalUser.getPushUserId()){
                        dto.setIsLastPioneer(2);
                    }
                    if (dto.getBiddingTwoTopPrice() != null) {
                        dto.setLastPrice(dto.getBiddingTwoTopPrice());
                    } else if (dto.getBiddingOneFirstPrice() != null) {
                        dto.setLastPrice(dto.getBiddingOneFirstPrice());
                    } else {

                    }
                }
            }

            //设置拒绝报价的渠道名称
            if (StringUtil.isNotBlank(dto.getChannelRefuseIds())){
                List<String> nameList = new ArrayList<>();
                for (String userID : dto.getChannelRefuseIds().split(",")) {
                    MjNormalUser mjNormalUser = normalUserMapper.selectByPrimaryKey(Integer.valueOf(userID));
                    nameList.add(mjNormalUser.getNickName());
                }
                dto.setChannelRefuserNames(nameList);
            }

            //返回商务提交的超时说明
            List<MjOrderTimeOutRemark> remarks = orderTimeOutRemarkMapper.selectByUserIdAndOrderId(null, req.getOrderId(),(short) 1);
            if (remarks != null && !remarks.isEmpty()){
                dto.setBusinessRemark(remarks);
            }

            //返回商开拓者、助理对超时的反馈意见
            List<MjOrderTimeOutRemark> remarks2 = orderTimeOutRemarkMapper.selectNormalUserByOrderId(null, req.getOrderId(),(short)2);
            if (remarks2 != null && !remarks2.isEmpty()){
                dto.setBusinessRemarkReply(remarks2);
            }

            //开拓者查看原表单
            if (ObjUtil.isNotNull(dto.getParentId())){
                List<ParentOrderDTO> parentOrderList = orderMapper.selectParentOrderList(dto.getParentId());
                if (CollUtil.isNotEmpty(parentOrderList)){
                    dto.setParentOrderList(parentOrderList);
                }
            }

            // 开拓者查看转移信息，查询转移转推的开拓者
            if (dto.getIsNextPush() != null && dto.getIsNextPush() == 2 &&  StringUtil.isNotBlank(dto.getNextPushUserIds())){
                String s = StringUtil.removeDuplicates(dto.getNextPushUserIds().split(","));
                String[] split = s.split(",");
                List<String> nextPushNames = new ArrayList<>();
                List<String> nextPushAssistants = new ArrayList<>();
                for (String nextPushUserId : split) {
                    MjNormalUser mjNormalUser = normalUserMapper.selectByPrimaryKey(Integer.valueOf(nextPushUserId));
                    // 检查查询结果是否有效
                    if (mjNormalUser != null) {
                        //判断是否助理
                        if (mjNormalUser.getIsAssistant() == (short)1){
                            nextPushNames.add(mjNormalUser.getNickName());
                        } else if(mjNormalUser.getIsAssistant() == (short)2){
                            nextPushAssistants.add(mjNormalUser.getNickName());
                        }
                    }
                }
                dto.setNextPushUserNames(nextPushNames);
                dto.setNextPushAssistantNames(nextPushAssistants);
            }
            //查询推送的人
            if (StringUtil.isNotBlank(dto.getPushUserIds())){
                StringBuilder userNamesBuilder = new StringBuilder();
                StringBuilder assistantNamesBuilder = new StringBuilder();
                String s = StringUtil.removeDuplicates(dto.getPushUserIds().split(","));
                for (String pushUserId : s.trim().split(",")) {
                    MjNormalUser mjNormalUser = normalUserMapper.selectByPrimaryKey(Integer.valueOf(pushUserId));
                    // 检查查询结果是否有效
                    if (mjNormalUser != null) {
                        //判断是否助理
                        if (mjNormalUser.getIsAssistant() == (short)1){
                            if (userNamesBuilder.length() > 0) {
                                userNamesBuilder.append(",");
                            }
                            userNamesBuilder.append(mjNormalUser.getNickName());
                        } else if(mjNormalUser.getIsAssistant() == (short)2){
                            if (assistantNamesBuilder.length() > 0) {
                                assistantNamesBuilder.append(",");
                            }
                            assistantNamesBuilder.append(mjNormalUser.getNickName());
                        }
                    }
                }
                dto.setPushUserName(userNamesBuilder.toString());
                dto.setPushAssistantName(assistantNamesBuilder.toString());
            }


            // 评级
            if (dto.getRateId() != null){
                OrderRateDTO rateDTO = orderManagerService.doGetRateContent(dto.getRateId());
                dto.setRate(rateDTO.getRate());
                dto.setRateContent(rateDTO.getAppContent());
            }

        }

        //中标开拓者
        String winBiddingName = orderMapper.selectWinBiddingName(req.getOrderId());
        dto.setWinBiddingName(winBiddingName);

        // 项目信息
        dto.setProjectMsg(projectMapper.selectMsgById(dto.getProjectId()));
        //订单状态和转移信息
        MjUserOrderStatus orderStatusObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(userId, req.getOrderId());
        //如果订单状态在userorderstatus中查询不到，渠道和开拓者都显示已结束
        if (orderStatusObj != null){
            dto.setOrderStatus(orderStatusObj.getOrderStatus());
            dto.setOrderIsNextPush(orderStatusObj.getIsNextPush());
        } else {
            dto.setOrderStatus(user.getUserType() == 1 ? 78 : 88);
            dto.setOrderIsNextPush((short) 1);
        }
        if (user.getUserType() == 4){
            List<Integer> userList = new ArrayList<>(Arrays.asList(9, 16, 17)); // 开拓者集合
            MjUserOrderStatus orderStatusObjFinalItem = null;
            for (Integer pushUserId : userList){
                MjUserOrderStatus orderStatusObjItem = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(pushUserId, req.getOrderId());
                if (orderStatusObjItem != null){
                    if ((orderStatusObjFinalItem == null || orderStatusObjFinalItem.getOrderStatus() < orderStatusObjItem.getOrderStatus())
                            && orderStatusObjItem.getOrderStatus() != 99 && orderStatusObjItem.getOrderStatus() != 90){
                        orderStatusObjFinalItem = orderStatusObjItem;
                    }
                }
            }
            if (orderStatusObjFinalItem != null){
                dto.setOrderStatus(orderStatusObjFinalItem.getOrderStatus());
                dto.setOrderIsNextPush(orderStatusObjFinalItem.getIsNextPush());
            }
        }
        APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
        ResultMessage resultMessage = ResultMessage.builder().setData(dto);
        successMessage.setResult(resultMessage);
        return successMessage;
    }

    public APPResultMessage<Object, List> doTransferPushUsers(int userId, CheckChannelUserDTO req) {
//        RedisUtil.setCacheObject("readOrder_" + req.getOrderId(), GlobalStatic.noRead2);
        MjOrder order = orderMapper.selectByPrimaryKey(req.getOrderId());
        if (order == null){
            return APPResultMessage.DATA_NOT_EXIST();
        }
        if (order.getIsNextPush() == 1){
            // 首次转移
            String userIds = "";
            List<MjUserOrder> mjUserOrders = userOrderMapper.selectListByOrderIdAndUserIdAndOrderType(req.getOrderId(), (short) 1, (short) 1);
            for (int i =0; i< mjUserOrders.size(); i ++){
                MjUserOrder userOrder = mjUserOrders.get(i);
                userIds = userIds + userOrder.getUserId() + (i < (mjUserOrders.size()-1) ? "," : "");
                userOrderMapper.updateStatusByOrderIdAndUserIdAndOrderType(req.getOrderId(),(short) 1,null, (short) 3);
            }
            String transferUserIds = req.getUserIds();
            if (StringUtil.isNotBlank(order.getTransferUserIds())){
                transferUserIds = order.getTransferUserIds() + "," + transferUserIds;
            }
//        order.setStatus((short) 1);
            order.setIsNextPush((short) 2);
            String nextPushUserIds = req.getUserIds();
            order.setNextPushUserIds(nextPushUserIds);
            order.setTransferUserIds(transferUserIds);
            order.setIsSubmitCheck((short) 1);
//        order.setSubmitCheckUserIds("");
            order.setFirstNextPushUserIds(userIds);
            orderMapper.updateByPrimaryKeySelective(order);
            //转移---转移前的助理也属于转移后的开拓者
            // 发起转移的开拓者和助理为已转移状态
            if (StringUtil.isNotBlank(order.getPushUserIds())){
                for (String pushUserId : order.getPushUserIds().trim().split(",")) {
                    MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                    orderStatusObj.setUpdateTime(new Date());
                    orderStatusObj.setIsNextPush((short) 2);
                    MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(Integer.valueOf(pushUserId), req.getOrderId());
                    if (isHaveObj != null){
                        orderStatusObj.setId(isHaveObj.getId());
                        mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
                    }
                }
            }
            // 转移后的开拓者和助理为新订单
            for (String pushUserId : req.getUserIds().trim().split(",")) {
                MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                orderStatusObj.setUserId(Integer.valueOf(pushUserId));
                orderStatusObj.setOrderId(req.getOrderId());
                orderStatusObj.setOrderStatus(79);
                orderStatusObj.setStatus((short) 1);
                orderStatusObj.setCreateTime(new Date());
                orderStatusObj.setIsNextPush((short) 1);
                MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(Integer.valueOf(pushUserId), req.getOrderId());
                if (isHaveObj != null){
                    orderStatusObj.setId(isHaveObj.getId());
                    mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
                } else {
                    mjUserOrderStatusMapper.insertSelective(orderStatusObj);
                }
            }
            //记录操作日志
//        logOperateMapper.addSelective(order.getProjectId(), order.getId(), userId,207,new Date(),1);
//        // TODO: 2023/8/31 0031 推送给其他开拓者，进行核价流程
//        sendSubscribeMsgTask.doPushMap(req.getUserIds(), order.getOrderKey(), order.getBrands(), "待核价", "该订单已转移给您", null);
            //项目状态改为 核价中-未分配给渠道
            projectMapper.updateStatusById(order.getProjectId(), (short) 2);
        }else if (order.getIsNextPush() == 2){
            order.setIsNextPush((short) 2);
            String transferUserIds = req.getUserIds();
            if (StringUtil.isNotBlank(order.getTransferUserIds())){
                transferUserIds = order.getTransferUserIds() + "," + transferUserIds;
            }
            String nextPushUserIds = req.getUserIds();
            if (StringUtil.isNotBlank(order.getNextPushUserIds())){
                nextPushUserIds = order.getNextPushUserIds() + "," + nextPushUserIds;
            }
            order.setNextPushUserIds(StringUtil.removeDuplicates(nextPushUserIds.split(",")));
            order.setTransferUserIds(StringUtil.removeDuplicates(transferUserIds.split(",")));
            orderMapper.updateByPrimaryKeySelective(order);
            for (String pushUserId : req.getUserIds().trim().split(",")) {
                MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                orderStatusObj.setUserId(Integer.valueOf(pushUserId));
                orderStatusObj.setOrderId(req.getOrderId());
                orderStatusObj.setOrderStatus(79);
                orderStatusObj.setStatus((short) 1);
                orderStatusObj.setCreateTime(new Date());
                orderStatusObj.setIsNextPush((short) 1);
                MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(Integer.valueOf(pushUserId), req.getOrderId());
                if (isHaveObj == null){
                    mjUserOrderStatusMapper.insertSelective(orderStatusObj);
                }
            }
        }
        // 如果没有使用时长，那么添加使用时长
        if (order.getPushSureCheckType() == 1 && order.getPushTime() != null){
//            orderMapper.updatePushSureCheckTypeById(order.getId());
            Long holidayNumByTime = dateUtils.getHolidayNumByTime(order.getPushTime().getTime(), new Date().getTime());
            orderMapper.updatePushUserHandleDiffTimeById(holidayNumByTime, order.getId());
        }
        return APPResultMessage.getSuccessMessage();
    }


    public APPResultMessage<Object, List> doBlindBoxRate(int userId, BlindBoxRateReq req) {
//        RedisUtil.setCacheObject("readOrder_" + req.getOrderId(), GlobalStatic.noRead3);
        String key = "doBlindBoxRate_" + req.getOrderId();
        String requestId = UUID.randomUUID().toString();
        boolean flag = LockUtil.tryGetDistributedLock(key, requestId);
        APPResultMessage message = APPResultMessage.getSuccessMessage();
        if (flag) {
            try {
                MjOrder mjOrder = orderMapper.selectByPrimaryKey(req.getOrderId());
                if (mjOrder.getIsBlindBox() != null && mjOrder.getIsBlindBox() == 2 && mjOrder.getBlindUserId() == userId && mjOrder.getStatus() == 6) {
                    orderMapper.updateTwoBlindBoxByOrderId(req.getOrderId(), req.getBlindBoxPrice(), req.getTakeAllStatus(), userId);
                }else {
                    int i = orderMapper.updateBlindBoxByOrderId(req.getOrderId(), req.getBlindBoxPrice(), req.getTakeAllStatus(), userId);
                    if (i != 1){
                        message = new APPResultMessage<>(6000, "该订单已提交过盲盒竞价");
                    }
                    // 修改项目状态
                    projectMapper.updateStatusById(mjOrder.getProjectId(), (short) 3);
                    //盲盒核价的开拓者为等待签单，没有渠道，竞价核价
                    MjOrder orderObj = orderMapper.selectByPrimaryKey(req.getOrderId());
                    Set<Integer> allPushUserIds = getAllPushUserIds(orderObj.getPushUserIds(), orderObj.getNextPushUserIds(), orderObj.getTransferUserIds(),orderObj.getBiddingPushUserIds());
                    for (Integer pushUserId : allPushUserIds) {
                        MjUserOrderStatus mjUserOrderStatus = new MjUserOrderStatus();
                        mjUserOrderStatus.setOrderStatus(82);
                        mjUserOrderStatus.setUpdateTime(new Date());
                        MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(pushUserId, req.getOrderId());
                        if (isHaveObj != null){
                            mjUserOrderStatus.setId(isHaveObj.getId());
                            mjUserOrderStatusMapper.updateByPrimaryKeySelective(mjUserOrderStatus);
                        }
                    }
                }
                if (StringUtil.isNotBlank(req.getGoods())){
                    orderBlindBoxMapper.updateStatusByOrderId(req.getOrderId());
                    List<GoodDTO> goodDTOS = JSON.parseArray(req.getGoods(), GoodDTO.class);
                    String s = sysLabelValueMapper.selectValueBySysIdAndReadOne(9);
                    for (GoodDTO dto : goodDTOS){
                        dto.setPrice(new BigDecimal(s));
                    }
                    orderBlindBoxMapper.insertBatch(goodDTOS, userId, req.getOrderId());
                }
                // 如果没有使用时长，那么添加使用时长
                if (mjOrder.getPushSureCheckType() == 1 && mjOrder.getPushTime() != null){
                    orderMapper.updatePushSureCheckTypeById(mjOrder.getId());
                    Long holidayNumByTime = dateUtils.getHolidayNumByTime(mjOrder.getPushTime().getTime(), new Date().getTime());
                    orderMapper.updatePushUserHandleDiffTimeById(holidayNumByTime, mjOrder.getId());
                }
                // TODO: 2023/8/31 0031 推送给发布者，订单已使用盲盒核价
                sendSubscribeMsgTask.doPushManageMap(String.valueOf(mjOrder.getCreateUserId()), mjOrder.getOrderKey(), mjOrder.getBrands(), "待确定", "该订单已进行盲盒竞价", null);
            }catch (Exception e){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                printErrorInfo(e);
                message = APPResultMessage.SYSTEM_ERROR();
            }finally {
                LockUtil.releaseDistributedLock(key, requestId);
                return message;
            }
        }else {
            return APPResultMessage.COMMIT_BUSY();
        }
    }
    //
    public APPResultMessage doCheckReferencePrice(Integer userId, BigDecimal referencePrice){
        APPResultMessage message = APPResultMessage.getSuccessMessage();
        MjNormalUser normalUser = normalUserMapper.selectByPrimaryKey(userId);
        if (null != normalUser && normalUser.getUserLevel() != null){
            SysLabelValue sysLabelValue = sysLabelValueMapper.selectByPrimaryKey(normalUser.getUserLevel());
            String desc = sysLabelValue.getDesc();
            if (StringUtil.isNotBlank(desc)){
                if (referencePrice.compareTo(new BigDecimal(desc)) > 0){
                    message = new APPResultMessage<>(6001, "您当前的等级不支持进行下一步操作，请升级后再处理");
                    return message;
                }
            }
        }
        return message;
    }

    //  提交核价/竞价方法
    public APPResultMessage<Object, List> doChannelCheckPrice(int userId, ChannelCheckPriceReq req) {
//        RedisUtil.setCacheObject("readOrder_" + req.getOrderId(), GlobalStatic.noRead2);
        APPResultMessage message = APPResultMessage.getSuccessMessage();
        try {
            boolean returnType = false;
            //如果是在竞价阶段
            if (req.getOrderType() != null && req.getOrderType() != 1){
                MjOrder mjOrder = orderMapper.selectByPrimaryKey(req.getOrderId());
                APPResultMessage appResultMessage = doCheckReferencePrice(userId, mjOrder.getReferencePrice());
                //如果没有权限进行竞价
                if (appResultMessage.getKey() != 1000){
                    returnType = true;
                    message = appResultMessage;
                }
                // 处理超过竞价时间进行提交的
                if (req.getOrderType() == 2){
                    // 第一次竞价
                    if (new Date().after(mjOrder.getBiddingOneEndTime())){
                        returnType = true;
                        message = new APPResultMessage(6001, "已超过竞价的截止时间，无法提交");
                    }
                }
                if (req.getOrderType() == 3){
                    long l = mjOrder.getBiddingTwoTimeSlot().multiply(new BigDecimal(3600)).multiply(new BigDecimal(1000)).longValue();
                    Long t = mjOrder.getBiddingOneEndTime().getTime() + l;
                    if (new Date().after(new Date(t))){
                        returnType = true;
                        message = new APPResultMessage(6001, "已超过竞价的截止时间，无法提交");
                    }
                }
            }
            //如果在核价阶段,或者有权限进行竞价
            if (!returnType) {
                //通过用户id,订单id,订单type,拿到这个userOrder
                MjUserOrder mjUserOrder = userOrderMapper.
                        selectIsHaveByOrderIdAndUserIdAndOrderType(userId, req.getOrderId(), req.getOrderType());
                //如果拿到的不是空,说明已经提交过一次价格了
                if (mjUserOrder != null) {
                    //更改userOrder的状态(指定orderId,orderType,userId),把之前的状态更改为作废
                    userOrderMapper.updateStatusByOrderIdAndUserIdAndOrderType
                            (req.getOrderId(), req.getOrderType(), userId, (short) 10);
                    //根据userOrderId更新userOrderGood的状态
                    userOrderGoodMapper.updateStatusByUserOrderId(mjUserOrder.getId());
                }

                BigDecimal totalPrice = BigDecimal.ZERO;
                //新建一个userorder对象,把信息填进去,再添加到表上
                MjUserOrder userOrder = new MjUserOrder();
                userOrder.setOrderId(req.getOrderId());
                userOrder.setUserId(userId);
                userOrder.setOrderType(req.getOrderType());
                userOrder.setStatus((short) 1);
                userOrder.setCreateTime(new Date());
                userOrder.setDiscountType(req.getDiscountType());
                userOrder.setIsConfirm((short) 1);

                //拿到req里的所有产品放到集合里
                List<GoodPriceReq> goodList = JSON.parseArray(req.getGoods(), GoodPriceReq.class);
                //遍历集合,把所有产品的价格相加
                for (GoodPriceReq goodPrice : goodList) {
                    totalPrice = totalPrice.add(goodPrice.getPrice().multiply(BigDecimal.valueOf(goodPrice.getNum())));
                }
                /*
                在这里判断是否为二次竞价,如果是,判断totalPrice是否大于第一次竞价的totalPrice
                 */
                //判断是否为二次竞价,是的话先拿到一次竞价的userOrder对象
                if (req.getOrderType() == 3){
                    MjUserOrder mjUserOrder1 = userOrderMapper.
                            selectIsHaveByOrderIdAndUserIdAndOrderType(userId, req.getOrderId(), (short) 2);
                    if (totalPrice.compareTo(mjUserOrder1.getTotalPrice()) < 0){
                        //返回提示:第二次竞价不得低于第一次竞价
                        message = new APPResultMessage<>(6001, "第二次竞价不得低于第一次竞价");
                        return message;
                    }
                }
                //把这条记录记录到userOrder表格里
                userOrderMapper.insertSelective(userOrder);

                //把goodList里面的产品放进表里userOrderGood表里
                userOrderGoodMapper.insertBatch(goodList, userOrder.getId());
                //更新userOrder表里的报价
                userOrderMapper.updateTotalPriceById(userOrder.getId(), totalPrice);
                // TODO: 2023/8/31 0031 通知开拓者，渠道已提交核价表单
                //通过订单id拿到订单
                MjOrder order = orderMapper.selectByPrimaryKey(req.getOrderId());
                //如果是核价阶段
                if (req.getOrderType() == 1) {
                    //拿到核价渠道的id
                    String checkUserIds = order.getSubmitCheckUserIds();
                    //如果id不是空的,说明有人核过价格
                    if (StringUtil.isNotBlank(checkUserIds)) {
                        //把这次核价的渠道id也拼接到之前的人里面
                        checkUserIds = checkUserIds + "," + userId;
                    //否则将核价渠道id改为当前提交价格的渠道id
                    } else {
                        checkUserIds = String.valueOf(userId);
                    }
                    //去重:把重复的渠道id去掉
                    String distinctUserIds = Arrays.stream(checkUserIds.split(","))
                            .distinct()
                            .collect(Collectors.joining(","));
                    //更新订单表中核价渠道信息
                    orderMapper.updateIsSubmitCheckById(req.getOrderId(), distinctUserIds);
                    //核价
                    // ---渠道报价，状态为已核价
                    MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                    orderStatusObj.setOrderStatus(72);
                    orderStatusObj.setUpdateTime(new Date());
                    //按userId,订单id查询出状态对象
                    MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.
                            selectObjByUserIdAndOrderId(userId, req.getOrderId());
                    //如果查询结果不为空
                    if (isHaveObj != null) {
                        //赋值id
                        orderStatusObj.setId(isHaveObj.getId());
                        //更新状态表
                        mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
                    }
                    // 所属的开拓者和助理未收到核价---
                    //开拓者
                    //--查出用户对象
                    MjNormalUser normalUser = normalUserMapper.selectByPrimaryKey(userId);
                    //--创建订单状态对象
                    MjUserOrderStatus orderStatusObj2 = new MjUserOrderStatus();
                    //设置状态对象的状态为81:收到核价
                    orderStatusObj2.setOrderStatus(81);
                    orderStatusObj2.setUpdateTime(new Date());
                    //通过开拓者id,订单id查询状态对象
                    MjUserOrderStatus isHaveObj2 = mjUserOrderStatusMapper.
                            selectObjByUserIdAndOrderId(normalUser.getPushUserId(), req.getOrderId());
                    //如果是等待签单状态82，则不进行修改,不是等待签单状态,进行if内修改
                    if (isHaveObj2 != null && isHaveObj2.getOrderStatus() != 82) {
                        //把创建的订单状态对象的id设置为已存在的状态对象的id
                        orderStatusObj2.setId(isHaveObj2.getId());
                        //更新状态对象表
                        mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj2);
                    }
                    //助理---判断是否为上一个状态--加一个sql修改助理userid,orderId,上一步的状态，和要修改的状态
                    List<MjNormalUser> assistantsList = normalUserMapper.selectAssistantsById(normalUser.getPushUserId());
                    if (assistantsList != null && assistantsList.size() > 0) {
                        for (MjNormalUser assistantObj : assistantsList) {
                            mjUserOrderStatusMapper.updateAssistant(assistantObj.getId(), req.getOrderId(), 80, 81);
                        }
                    }
                    //项目状态改为 核价中-已反馈未确认
                    projectMapper.updateStatusById(order.getProjectId(), (short) 7);
                //如果在一次竞价阶段
                } else if (req.getOrderType() == 2) {
                    //查询出报价的渠道们的id
                    String userIds = order.getBiddingFirstUserIds();
                    //如果查出结果不为空
                    if (StringUtil.isNotBlank(userIds)) {
                        //把查到的id拼接到传过来的参数userId上
                        userIds = userIds + "," + userId;
                    } else {
                        //查到结果为空,就把传过来的userId赋值
                        userIds = String.valueOf(userId);
                    }
                    //新增去重--
                    String distinctUserIds = Arrays.stream(userIds.split(","))
                            .distinct()
                            .collect(Collectors.joining(","));

                    //更新订单表的第一次提交报价的渠道信息
                    orderMapper.updateBiddingFirstUserIdsById(req.getOrderId(), distinctUserIds);
                //如果在二次竞价阶段
                } else if (req.getOrderType() == 3) {
                    //查出参与二次报价的用户信息
                    String userIds = order.getBiddingSecondUserIds();
                    //如果不为空
                    if (StringUtil.isNotBlank(userIds)) {
                        //拼接
                        userIds = userIds + "," + userId;
                    } else {
                        //为空,赋值
                        userIds = String.valueOf(userId);
                    }
                    //新增去重
                    String distinctUserIds = Arrays.stream(userIds.split(","))
                            .distinct()
                            .collect(Collectors.joining(","));
                    //更新订单表的
                    orderMapper.updateBiddingSecondUserIdsById(req.getOrderId(), distinctUserIds);
                }
                //查询开拓者
                String pushUserIds = order.getPushUserIds();
                //如果转移过
                if (order.getIsNextPush() != null && order.getIsNextPush() == 2) {
                    //拼接开拓者
                    pushUserIds = pushUserIds + ',' + order.getNextPushUserIds();
                }

                String title = "核价";
                //订单type不为空
                if (req.getOrderType() != null) {
                    if (req.getOrderType() == 1) {
                        title = "核价";
                    } else if (req.getOrderType() == 2) {
                        title = "第一次竞价";
                    } else if (req.getOrderType() == 3) {
                        title = "第二次竞价";
                    }
                }
                //
                sendSubscribeMsgTask.doPushMap(pushUserIds, order.getOrderKey(), order.getBrands(),
                        title + "中", "该订单已提交" + title, null);

            }
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            printErrorInfo(e);
            message = APPResultMessage.SYSTEM_ERROR();
        }finally {
            return message;
        }
    }

    public APPResultMessage<Object, List> doSureChannelCheckPrice(int userId, Short userType, OrderSureCheckReq req) {
//        RedisUtil.setCacheObject("readOrder_" + req.getOrderId(), GlobalStatic.noRead3);
        // 修改订单的评级
        //创建阶段
        if (req.getChooseSetRateId() != null){
            APPResultMessage appResultMessage = doSetAppOrderRate(userId, req.getOrderId(), req.getChooseSetRateId());
            if (appResultMessage.getKey() != 1000){
                return appResultMessage;
            }
        }
        MjOrder order = orderMapper.selectByPrimaryKey(req.getOrderId());
        String userIds = order.getPushChannelUserIds();
        List<MjUserOrder> mjUserOrders = userOrderMapper.selectListByOrderIdAndUserIdAndOrderType(req.getOrderId(), (short) 1, (short) 1);
        if (!BeanUtil.isNullList(mjUserOrders)){
            userIds = userIds + ",";
        }
        for (int i =0; i< mjUserOrders.size(); i ++){
            MjUserOrder userOrder = mjUserOrders.get(i);
            userIds = userIds + userOrder.getUserId() + (i < (mjUserOrders.size()-1) ? "," : "");
        }
        if (StringUtil.isNotBlank(userIds)){
            String distinctUserIds = Arrays.stream(userIds.split(","))
                    .distinct()
                    .collect(Collectors.joining(","));
            orderMapper.updatePushChannelUserIdsByOrderId(distinctUserIds, req.getOrderId());
        }
        //新增核价信息
        MjNormalUser user = normalUserMapper.selectByPrimaryKey(userId);
        MjUserOrderCheck userOrderCheck = new MjUserOrderCheck();
        userOrderCheck.setUserId(userId);
        userOrderCheck.setOrderId(req.getOrderId());
        userOrderCheck.setStatus((short) 1);
        userOrderCheck.setCreateTime(new Date());
        MjProject mjProject = projectMapper.selectByPrimaryKey(order.getProjectId());

        //创建阶段
        MjProjectStage mjProjectStage = new MjProjectStage();
        MjProjectStage stage = projectStageMapper.selectOne(
                new LambdaQueryWrapper<MjProjectStage>()
                        .eq(MjProjectStage::getProjectId, order.getProjectId())
                        .eq(MjProjectStage::getIsCurrent, 1)
        );

        mjProjectStage.setProjectId(order.getProjectId());
        mjProjectStage.setIsCurrent(true);
        mjProjectStage.setName(ProjectStatusEnum.WAIT_PACKAGE.getName());
        mjProjectStage.setCode(ProjectStatusEnum.WAIT_PACKAGE.getCode());
        mjProjectStage.setSort(stage.getSort() + 1);
        mjProjectStage.setCreateTime(new Date());

        stage.setIsCurrent(false);
        stage.setEndTime(new Date());

        projectStageMapper.insert(mjProjectStage);

        order.setStageId(
                (order.getStageId() == null || order.getStageId().trim().isEmpty())
                        ? String.valueOf(mjProjectStage.getId())
                        : Stream.concat(
                                Arrays.stream(order.getStageId().split(",")).map(String::trim),
                                Stream.of(String.valueOf(mjProjectStage.getId()))
                        )
                        .filter(s -> !s.isEmpty())
                        .distinct()
                        .collect(Collectors.joining(","))
        );
        orderMapper.updateById(order);

        projectStageMapper.updateById(stage);

        //判断是否为助理
        if (user.getIsAssistant() != null && user.getIsAssistant() == 2){
            //如果是助理只改 变现价格
            userOrderCheck.setCashDiscountType(req.getCashDiscountType());
            if (req.getCashDiscountType() == 1){
                //如果是选择折扣，计算
                userOrderCheck.setCheckCashPrice(String.valueOf(order.getTotalPrice()
                        .multiply(new BigDecimal(req.getCheckCashPrice()))
                        .multiply(new BigDecimal("0.1"))
                        .setScale(2, RoundingMode.HALF_UP)));
            } else {
                userOrderCheck.setCheckCashPrice(req.getCheckCashPrice());
            }
            userOrderCheck.setIsAssistant((short) 2);
            userOrderCheck.setIsConfirm((short) 1);
            userOrderCheck.setChannelIds(req.getChannelIds());
            //根据渠道id找到 所属开拓者状态为收到核价
            //只有订单状态在竞价前确认签单才会改变状态
            if (order.getStatus() <= 3) {
                MjNormalUser mjNormalUser = normalUserMapper.selectByPrimaryKey(Integer.valueOf(req.getChannelIds()));
                MjUserOrderStatus mjUserOrderStatus = new MjUserOrderStatus();
                mjUserOrderStatus.setOrderStatus(81);
                mjUserOrderStatus.setUpdateTime(new Date());
                MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(mjNormalUser.getPushUserId(), req.getOrderId());
                if (isHaveObj != null){
                    mjUserOrderStatus.setId(isHaveObj.getId());
                    mjUserOrderStatusMapper.updateByPrimaryKeySelective(mjUserOrderStatus);
                }
            }
//            // 添加进程，并通知选品人
//            List<ProcessToUser> toUserList = new ArrayList<>();
//            ProcessToUser toUser = new ProcessToUser();
//            toUser.setUserType((short) 3);
//            toUser.setUserId(mjProject.getProductSelectionManagerId());
//            toUserList.add(toUser);
//            processManageService.doAddProcess(mjProject.getId(), userId, userType, ProcessEnum.submitCheckOrder, toUserList);
        } else {
            userOrderCheck.setCheckRemark(req.getCheckRemark());
            //变现价格
            userOrderCheck.setCashDiscountType(req.getCashDiscountType());
            if (req.getCashDiscountType() == 1){
                //如果是选择折扣，计算
                userOrderCheck.setCheckCashPrice(String.valueOf(order.getTotalPrice()
                        .multiply(new BigDecimal(req.getCheckCashPrice()))
                        .multiply(new BigDecimal("0.1"))
                        .setScale(2, RoundingMode.HALF_UP)));
            } else {
                userOrderCheck.setCheckCashPrice(req.getCheckCashPrice());
            }
            //建议成本
            userOrderCheck.setCostDiscountType(req.getCostDiscountType());
            if (req.getCostDiscountType() == 1){
                //如果是选择折扣，计算
                userOrderCheck.setCheckCostPrice(String.valueOf(order.getTotalPrice()
                        .multiply(new BigDecimal(req.getCheckCostPrice()))
                        .multiply(new BigDecimal("0.1"))
                        .setScale(2, RoundingMode.HALF_UP)));
            } else {
                userOrderCheck.setCheckCostPrice(req.getCheckCostPrice());
            }
            userOrderCheck.setIsAssistant((short) 1);

            //同时修改order表的核价信息和状态
            orderMapper.updateCheckMsgByOrderId(order.getId(),new BigDecimal(userOrderCheck.getCheckCashPrice()),userOrderCheck.getCheckCostPrice(),req.getCheckRemark());
            if (order.getStatus() <= 3){
                //订单总状态---只要有开拓者确认过核价了，在确认核价这里，订单状态不再改变
                orderMapper.updateStatusByOrderId(req.getOrderId(), (short) 3);
                //全部的开拓者为等待签单，包括助理
                //只有订单状态在竞价前确认签单才会改变状态
                Set<Integer> allPushUserIds = getAllPushUserIds(order.getPushUserIds(), order.getNextPushUserIds(), order.getTransferUserIds(),order.getBiddingPushUserIds());
                for (Integer pushUserId : allPushUserIds) {
                    MjUserOrderStatus mjUserOrderStatus = new MjUserOrderStatus();
                    mjUserOrderStatus.setOrderStatus(82);
                    mjUserOrderStatus.setUpdateTime(new Date());
                    MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(pushUserId, req.getOrderId());
                    if (isHaveObj != null){
                        mjUserOrderStatus.setId(isHaveObj.getId());
                        mjUserOrderStatusMapper.updateByPrimaryKeySelective(mjUserOrderStatus);
                    }
                }
            }
            //更改项目状态
            projectMapper.updateStatusById(order.getProjectId(), (short) 3);
            // 当为开拓者，不是助理时，判断是否填写过开拓者确认反馈的时间，没有填写就添加
            if (order.getPushSureCheckType() != null && order.getPushSureCheckType() == 1 && order.getPushSureCheckTime() == null){
                orderMapper.updatePushSureCheckTimeById(order.getId());
            }
            // 如果没有使用时长，那么添加使用时长
            if (order.getPushSureCheckType() == 1 && order.getPushTime() != null){
                Long holidayNumByTime = dateUtils.getHolidayNumByTime(order.getPushTime().getTime(), new Date().getTime());
                orderMapper.updatePushUserHandleDiffTimeById(holidayNumByTime, order.getId());
            }
            //订单下的所有渠道为已确认核价
            userOrderMapper.updateIsConfirmByOrderIdAndUserIdAndOrderType(req.getOrderId(), (short) 1, userId, (short) 2);
            //订单下的所有助理为已确认核价
            userOrderCheckMapper.updateAssistantConfirm(req.getOrderId(), (short) 2);
            // 通知该项目所属的执行
            String msg = mjProject.getName() + "已确认反馈，请及时处理";
            webSocketServer.sendMsgToUserId(msg, mjProject.getPermissionId(), (short) 2);


//            // 添加进程，并通知项目经理
//            MjBusinessPerson businessPerson = businessPersonMapper.selectByPrimaryKey(mjProject.getBusinessId());
//            List<ProcessToUser> toUserList = new ArrayList<>();
//            ProcessToUser toUser = new ProcessToUser();
//            toUser.setUserType((short) 3);
//            toUser.setUserId(businessPerson.getBusinessAssistantId());
//            toUserList.add(toUser);
//            processManageService.doAddProcess(mjProject.getId(), userId, userType, ProcessEnum.sureCheckOrder, toUserList);


            // 通知
            Map<String, Object> templateParams = new HashMap<>();
            notifyService.doSendNotifyByRoleId(userId, userType, "sureCheckPrice", templateParams, order.getProjectId());
        }
        userOrderCheckMapper.insertSelective(userOrderCheck);
        //记录操作日志
        logOperateMapper.addSelective(order.getProjectId(), order.getId(), userId,208,new Date(),1);

        // TODO: 2023/8/31 0031 通知开发者，开拓者已确认核价表单，进入竞价阶段
        sendSubscribeMsgTask.doPushManageMap(String.valueOf(order.getCreateUserId()), order.getOrderKey(), order.getBrands(), "核价等待中", "请查看核价", null);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage<Object, List> doSureBiddingEndTime(int userId, BiddingEndTimeReq req) {
//        RedisUtil.setCacheObject("readOrder_" + req.getOrderId(), GlobalStatic.noRead2);
        MjOrder order = orderMapper.selectByPrimaryKey(req.getOrderId());
        if (ObjUtil.isNotNull(order.getIsHasChild()) && order.getIsHasChild() == 2){
            return new APPResultMessage<>(6001, "父表单不可竞价，请先删除子表单");
        }
        List<MjNormalUser> users = normalUserMapper.selectListByUserType((short) 2);
        List<Integer> idList = new ArrayList<>();
//        if (order.getIsNextPush() != null && order.getIsNextPush() == 2){
//            idList = users.stream().filter(s -> s.getId() != userId).map(MjNormalUser::getId).collect(Collectors.toList());
//        }else {
//            idList = users.stream().map(MjNormalUser::getId).collect(Collectors.toList());
//        }
        idList = users.stream().map(MjNormalUser::getId).collect(Collectors.toList());
        //开拓者为一次竞价中状态
        for (Integer pushUserId : idList) {
            MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(pushUserId, req.getOrderId());
            if (isHaveObj != null){
                MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                orderStatusObj.setOrderStatus(86);
                orderStatusObj.setUpdateTime(new Date());
                orderStatusObj.setId(isHaveObj.getId());
                mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
            } else {
                MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                orderStatusObj.setUserId(pushUserId);
                orderStatusObj.setOrderId(req.getOrderId());
                orderStatusObj.setOrderStatus(86);
                orderStatusObj.setCreateTime(new Date());
                orderStatusObj.setStatus((short)1);
                orderStatusObj.setIsNextPush((short)1);
                mjUserOrderStatusMapper.insertSelective(orderStatusObj);
            }
        }
        String ids = StringUtils.join(idList, ",");
        order.setBiddingPushUserIds(ids);
        //设置其他开拓者的其他订单状态
        if (ObjUtil.isNotNull(order.getParentId())){
            MjOrder parentOrder = orderMapper.selectByPrimaryKey(order.getParentId());
            moveStatus(order,order.getParentId(),idList);
            //设置父订单一次竞价参与的开拓者，方便结束订单时候改变状态
            if (StrUtil.isBlank(parentOrder.getBiddingPushUserIds())){
                parentOrder.setBiddingPushUserIds(ids);
            }
        }

        String s = sysLabelValueMapper.selectValueBySysIdAndReadOne(1);
        order.setBiddingTwoTimeSlot(new BigDecimal(s));
        order.setIsDiscount(req.getIsDiscount());
        if (req.getIsDiscount() != null){
            if (req.getIsDiscount() == 1){
                order.setDiscountPrice(req.getDiscountPrice());
                order.setReferencePrice(order.getTotalPrice().multiply(req.getDiscountPrice()).multiply(new BigDecimal(0.1)));
            }else {
                order.setDiscountPrice(req.getDiscountPrice().divide(order.getTotalPrice(), 6, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(10)).setScale(2, BigDecimal.ROUND_HALF_UP));
                order.setReferencePrice(req.getDiscountPrice());
            }
        }
        orderMapper.updateByPrimaryKeySelective(order);
        orderMapper.updateBiddingOneEndTimeByOrderId(new Date(req.getEndTime()),req.getOrderId());

        //记录操作日志
        logOperateMapper.addSelective(order.getProjectId(), order.getId(), userId,201,new Date(),1);
        // TODO: 2023/8/31 0031 通知所有开拓者，进入第一次竞价阶段
        String[] exportUserIds = null;
        if (order.getIsNextPush() != null && order.getIsNextPush() == 2){
            exportUserIds = order.getTransferUserIds().split(",");
        }
        String pushUserIds = normalUserMapper.selectAllPushIds(exportUserIds);
        sendSubscribeMsgTask.doPushMap(pushUserIds, order.getOrderKey(), order.getBrands(), "第一次竞价中", "该项目订单已确认竞价截止时间，请开始分配渠道进行竞价", null);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage<Object, List> doSurePushChannelUser(int userId, CheckChannelUserDTO req) {
//        RedisUtil.setCacheObject("readOrder_" + req.getOrderId(), GlobalStatic.noRead1);
        String key = "doSurePushChannelUser_" + req.getOrderId();
        String requestId = UUID.randomUUID().toString();
        boolean flag = LockUtil.tryGetDistributedLock(key, requestId);
        APPResultMessage message = APPResultMessage.getSuccessMessage();
        if (flag) {
            MjOrder order = orderMapper.selectByPrimaryKey(req.getOrderId());
            if (StringUtil.isBlank(order.getBiddingHasPushUserIds())){
                order.setBiddingHasPushUserIds(String.valueOf(userId));
            }else {
                order.setBiddingHasPushUserIds(order.getBiddingHasPushUserIds() + "," + String.valueOf(userId));
            }
            if (StringUtil.isBlank(order.getBiddingPushChannelUserIds())){
                order.setBiddingPushChannelUserIds(req.getUserIds());
            }else {
                order.setBiddingPushChannelUserIds(order.getBiddingPushChannelUserIds() + "," + req.getUserIds());
            }
            //渠道状态为一次竞价中
            if (StringUtil.isNotBlank(req.getUserIds())){
                for (String userIds : req.getUserIds().trim().split(",")) {
                    if (StringUtil.isNotBlank(userIds)){
                        MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(Integer.valueOf(userIds), req.getOrderId());
                        if (isHaveObj != null){
                            MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                            orderStatusObj.setOrderStatus(74);
                            orderStatusObj.setUpdateTime(new Date());
                            orderStatusObj.setId(isHaveObj.getId());
                            mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
                        } else {
                            MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                            orderStatusObj.setUserId(Integer.valueOf(userIds));
                            orderStatusObj.setOrderId(req.getOrderId());
                            orderStatusObj.setOrderStatus(74);
                            orderStatusObj.setCreateTime(new Date());
                            orderStatusObj.setStatus((short)1);
                            orderStatusObj.setIsNextPush((short)1);
                            mjUserOrderStatusMapper.insertSelective(orderStatusObj);
                        }
                    }
                }
            }

            orderMapper.updateByPrimaryKeySelective(order);
            sendSubscribeMsgTask.doPushMap(order.getBiddingPushChannelUserIds(), order.getOrderKey(), order.getBrands(), "竞价中", "该项目订单可以进行竞价", null);
            LockUtil.releaseDistributedLock(key, requestId);
            return message;
        }else {
            return APPResultMessage.COMMIT_BUSY();
        }
    }

    public APPResultMessage<Object, List> doUpdateSureBiddingEndTime(int userId, BiddingEndTimeReq req) {
//        RedisUtil.setCacheObject("readOrder_" + req.getOrderId(), GlobalStatic.noRead1);
        orderMapper.updateBiddingOneEndTimeByOrderId(new Date(req.getEndTime()),req.getOrderId());
        String s = DateUtil.getyyyy_MM_ddHHmm(new Date(req.getEndTime()));
        MjOrder order = orderMapper.selectByPrimaryKey(req.getOrderId());
        order.setIsDiscount(req.getIsDiscount());
        if (req.getIsDiscount() != null){
            if (req.getIsDiscount() == 1){
                order.setDiscountPrice(req.getDiscountPrice());
                order.setReferencePrice(order.getTotalPrice().multiply(req.getDiscountPrice()).multiply(new BigDecimal(0.1)));
            }else {
                order.setDiscountPrice(req.getDiscountPrice().divide(order.getTotalPrice(), 6, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(10)).setScale(2, BigDecimal.ROUND_HALF_UP));
                order.setReferencePrice(req.getDiscountPrice());
            }
        }
        orderMapper.updateByPrimaryKeySelective(order);
        String[] exportUserIds = null;
        if (order.getIsNextPush() != null && order.getIsNextPush() == 2){
            exportUserIds = order.getNextPushUserIds().split(",");
        }
        String pushUserIds = normalUserMapper.selectAllPushIds(exportUserIds);
        String biddingPushChannelUserIds = order.getBiddingPushChannelUserIds();
        pushUserIds = pushUserIds + "," + biddingPushChannelUserIds;
        //记录操作日志
        logOperateMapper.addSelective(order.getProjectId(), order.getId(), userId,202,new Date(),1);
        sendSubscribeMsgTask.doPushMap(pushUserIds, order.getOrderKey(), order.getBrands(), "第一次竞价中", "该项目订单已修改竞价截止时间，时间截止到" + s, null);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage<Object, List> doStartTwoBidding(int userId, OrderIdReq req) {
        MjOrder order = orderMapper.selectByPrimaryKey(req.getOrderId());
        MjNormalUser normalUser = normalUserMapper.selectByPrimaryKey(userId);
        if (null != normalUser && normalUser.getUserLevel() != null){
            SysLabelValue sysLabelValue = sysLabelValueMapper.selectByPrimaryKey(normalUser.getUserLevel());
            String desc = sysLabelValue.getDesc();
            if (StringUtil.isNotBlank(desc)){
                if (order.getReferencePrice().compareTo(new BigDecimal(desc)) > 0){
                    return new APPResultMessage<>(6001, "您当前的等级不支持进行下一步操作，请升级后再处理");
                }
            }
        }
//        RedisUtil.setCacheObject("readOrder_" + req.getOrderId(), GlobalStatic.noRead1);
        String key = "doStartTwoBidding_" + req.getOrderId();
        String requestId = UUID.randomUUID().toString();
        boolean flag = LockUtil.tryGetDistributedLock(key, requestId);
        APPResultMessage message = APPResultMessage.getSuccessMessage();
        if (flag) {
            String endTime = sysLabelValueMapper.selectValueBySysIdAndReadOne(19);
            orderMapper.updateStartTwoBidding(req.getOrderId(), userId, endTime);
            LockUtil.releaseDistributedLock(key, requestId);
            return message;
        }else {
            return APPResultMessage.COMMIT_BUSY();
        }
    }

    public APPResultMessage<Object, List> doJoinTwoBidding(int userId, OrderIdReq req) {
//        RedisUtil.setCacheObject("readOrder_" + req.getOrderId(), GlobalStatic.noRead1);
        MjOrder order = orderMapper.selectByPrimaryKey(req.getOrderId());
        MjNormalUser normalUser = normalUserMapper.selectByPrimaryKey(userId);
        if (null != normalUser && normalUser.getUserLevel() != null){
            SysLabelValue sysLabelValue = sysLabelValueMapper.selectByPrimaryKey(normalUser.getUserLevel());
            String desc = sysLabelValue.getDesc();
            if (StringUtil.isNotBlank(desc)){
                if (order.getReferencePrice().compareTo(new BigDecimal(desc)) > 0){
                    return new APPResultMessage<>(6001, "您当前的等级不支持进行下一步操作，请升级后再处理");
                }
            }
        }
        String userIds = String.valueOf(userId);
        if(StringUtil.isNotBlank(order.getBiddingStartTwoUserIds())){
            userIds = order.getBiddingStartTwoUserIds() + "," + userIds;
        }
        order.setBiddingStartTwoUserIds(userIds);
        orderMapper.updateByPrimaryKeySelective(order);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage<Object, List> doRefuseOrder(int userId, RefuseOrderReq req) {
        MjOrder orderObj = orderMapper.selectByPrimaryKey(req.getOrderId());
        //子订单记录结束时间
        orderMapper.updateRefuseReasonById(req.getOrderId(), req.getReason());
        //父订单记录结束时间
        if (ObjUtil.isNotNull(orderObj.getParentId())){
            orderMapper.updateEndTime(orderObj.getParentId(),new Date());
        }
        //开拓者拒绝订单，其他开拓者都为已拒绝，渠道为已结束
        Set<Integer> allPushUserIds = getAllPushUserIds(orderObj.getPushUserIds(), orderObj.getNextPushUserIds(), orderObj.getTransferUserIds(),orderObj.getBiddingPushUserIds());
        for (Integer pushUserId : allPushUserIds) {
            MjUserOrderStatus mjUserOrderStatus = new MjUserOrderStatus();
            mjUserOrderStatus.setOrderStatus(90);
            mjUserOrderStatus.setUpdateTime(new Date());
            MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(pushUserId, req.getOrderId());
            if (isHaveObj != null){
                mjUserOrderStatus.setId(isHaveObj.getId());
                mjUserOrderStatusMapper.updateByPrimaryKeySelective(mjUserOrderStatus);
            }
        }
        //渠道为已结束
        if (StringUtil.isNotBlank(orderObj.getPushChannelUserIds())){
            for (String channelId : orderObj.getPushChannelUserIds().split(",")) {
                MjUserOrderStatus mjUserOrderStatus = new MjUserOrderStatus();
                mjUserOrderStatus.setOrderStatus(78);
                mjUserOrderStatus.setUpdateTime(new Date());
                MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(Integer.valueOf(channelId), req.getOrderId());
                if (isHaveObj != null){
                    mjUserOrderStatus.setId(isHaveObj.getId());
                    mjUserOrderStatusMapper.updateByPrimaryKeySelective(mjUserOrderStatus);
                }
            }
        }
        // 如果没有使用时长，那么添加使用时长
        if (orderObj.getPushSureCheckType() == 1 && orderObj.getPushTime() != null){
            orderMapper.updatePushSureCheckTypeById(orderObj.getId());
            Long holidayNumByTime = dateUtils.getHolidayNumByTime(orderObj.getPushTime().getTime(), new Date().getTime());
            orderMapper.updatePushUserHandleDiffTimeById(holidayNumByTime, orderObj.getId());
        }
        return APPResultMessage.getSuccessMessage();
    }

    public  Set<Integer> getAllPushUserIds(String pushUserIds,String nextPushUserIds,String transferUserIds,String biddingPushUserIds) {
        Set<Integer> userIdSet= new HashSet<>();
        if (StringUtil.isNotBlank(pushUserIds)){
            List<Integer> str1 = Arrays.stream(pushUserIds.split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            userIdSet.addAll(str1);
        }

        if (StringUtil.isNotBlank(nextPushUserIds)){
            List<Integer> str2 = Arrays.stream(nextPushUserIds.split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            userIdSet.addAll(str2);
        }
        if (StringUtil.isNotBlank(transferUserIds)){
            List<Integer> str3 = Arrays.stream(transferUserIds.split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            userIdSet.addAll(str3);
        }
        if (StringUtil.isNotBlank(biddingPushUserIds)){
            List<Integer> str4 = Arrays.stream(biddingPushUserIds.split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            userIdSet.addAll(str4);
        }
        return userIdSet;
    }


    public APPResultMessage doUpdateOrderRealPrice(int userId, UpdateOrderRealPriceReq req) {
        BigDecimal blindBoxRealPrice = req.getBlindBoxRealPrice() == null ? BigDecimal.ZERO : req.getBlindBoxRealPrice();
        BigDecimal saleRealPrice = req.getSaleRealPrice() == null ? BigDecimal.ZERO : req.getSaleRealPrice();
        BigDecimal totalPrice = blindBoxRealPrice.add(saleRealPrice);
        orderMapper.updateRealPriceById(req.getOrderId(), blindBoxRealPrice, saleRealPrice, totalPrice, req.getRealRemark());
        //记录操作日志
        MjOrder mjOrder = orderMapper.selectByPrimaryKey(req.getOrderId());
        logOperateMapper.addSelective(mjOrder.getProjectId(), req.getOrderId(), userId,209,new Date(),1);
        return APPResultMessage.getSuccessMessage();
    }


    public APPResultMessage doUpdateProjectOutGoodMsg(int userId, UpdateProjectOutGoodReq req) {
        MjProject project = projectMapper.selectByPrimaryKey(req.getProjectId());
        ProjectOutGoodMsg projectOutGoodMsg = new ProjectOutGoodMsg();
        BeanUtils.copyProperties(req, projectOutGoodMsg);
        String msg = project.getProjectOutGoodMsg();
        BigDecimal outGoodPrice = req.getProjectOutGoodPrice();
        BigDecimal outGoodSomePrice = req.getProjectOutGoodSomePrice();
        String s = DateUtil.getyyyyMMddSlash(new Date(req.getTime()));
        String remark = "";
        projectOutGoodMsg.setUserId(userId);
        if (StringUtil.isNotBlank(msg)){
            List<ProjectOutGoodMsg> list = JSON.parseArray(msg, ProjectOutGoodMsg.class);
            list.add(0,projectOutGoodMsg);
            project.setProjectOutGoodMsg(JSON.toJSONString(list));
            outGoodPrice = outGoodPrice.add(project.getProjectOutGoodPrice() != null ? project.getProjectOutGoodPrice() : BigDecimal.ZERO);
            outGoodSomePrice = outGoodSomePrice.add(project.getProjectOutGoodSomePrice() != null ? project.getProjectOutGoodSomePrice() : BigDecimal.ZERO);
            remark = project.getProjectOutGoodRemark();
        }else {
            List<ProjectOutGoodMsg> list = new ArrayList<>();
            list.add(projectOutGoodMsg);
            project.setProjectOutGoodMsg(JSON.toJSONString(list));
        }
        project.setProjectOutGoodRemark(remark + s + "：" + req.getProjectOutGoodRemark() + "；");
        project.setProjectOutGoodPrice(outGoodPrice);
        project.setProjectOutGoodSomePrice(outGoodSomePrice);
        project.setUpdateTime(new Date());
        projectMapper.updateByPrimaryKeySelective(project);
        //记录操作日志

        logOperateMapper.addSelective(req.getProjectId(), null, userId,210,new Date(),1);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage doRefuseChannelOrder(int userId, OrderIdReq req) {
        MjOrder order = orderMapper.selectByPrimaryKey(req.getOrderId());
        String refuseChannelIds = order.getChannelRefuseIds();
        if (StringUtil.isBlank(refuseChannelIds)){
            order.setChannelRefuseIds(String.valueOf(userId));
        }else {
            refuseChannelIds = refuseChannelIds + "," + userId;
            order.setChannelRefuseIds(refuseChannelIds);
        }
        orderMapper.updateByPrimaryKeySelective(order);
        //拒绝的渠道为已拒绝状态
        MjUserOrderStatus mjUserOrderStatus = new MjUserOrderStatus();
        mjUserOrderStatus.setOrderStatus(94);
        mjUserOrderStatus.setUpdateTime(new Date());
        MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(userId, req.getOrderId());
        if (isHaveObj != null){
            mjUserOrderStatus.setId(isHaveObj.getId());
            mjUserOrderStatusMapper.updateByPrimaryKeySelective(mjUserOrderStatus);
        }
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage getHomeShowNum(int userId) {
        MjNormalUser normalUser = normalUserMapper.selectByPrimaryKey(userId);
        String status1 = "";    // 待处理
        String status2 = "";    // 竞价中
        Map<Integer, Integer> numMap = new HashMap<>();
        Map map = new HashMap();
        Integer status1Num = 0;
        Integer status2Num = 0;
        if (normalUser.getUserType() == 1){
            status1 = "71,73";
            status2 = "74,75,76";
            numMap.put(71, 0);
            numMap.put(73, 0);
            numMap.put(74, 0);
            numMap.put(75, 0);
            numMap.put(76, 0);
        }else if (normalUser.getUserType() == 2){
            status1 = "79,81,83,85";
            status2 = "86,87";
            numMap.put(79, 0);
            numMap.put(81, 0);
            numMap.put(83, 0);
            numMap.put(85, 0);
            numMap.put(86, 0);
            numMap.put(87, 0);
        }
        Integer showUserId = userId;
        List statuses1 = new ArrayList();
        if(StringUtil.isNotBlank(status1)){
            String[] split = status1.split(",");
            for (int i=0;i<split.length;i++){
                statuses1.add(split[i]);
            }
        }
        List<ManagerOrderDTO> dtos = orderMapper.selectAppListByUserId(showUserId,normalUser.getUserType(),null,null,null,
                null,null, null,null,
                null, null,
                statuses1);
        status1Num = dtos.size();
        List statuses2 = new ArrayList();
        if(StringUtil.isNotBlank(status2)){
            String[] split = status2.split(",");
            for (int i=0;i<split.length;i++){
                statuses2.add(split[i]);
            }
        }
        List<ManagerOrderDTO> dtos2 = orderMapper.selectAppListByUserId(showUserId,normalUser.getUserType(),null,null,null,
                null,null, null,null,
                null, null,
                statuses2);
        status2Num = dtos2.size();
        map.put("status1", status1Num);
        map.put("status2", status2Num);
        APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
        ResultMessage resultMessage = ResultMessage.builder().setData(map);
        successMessage.setResult(resultMessage);
        return successMessage;
    }

    public APPResultMessage getHomeShowNum2(int userId) {
        MjNormalUser normalUser = normalUserMapper.selectByPrimaryKey(userId);
        String statuses = "";
        String userSearch = "$.user_" + userId;
        Map<Integer, Integer> numMap = new HashMap<>();
        if (normalUser.getUserType() == 1){
            statuses = "71,73,74,75,76";
            numMap.put(71, 0);
            numMap.put(73, 0);
            numMap.put(74, 0);
            numMap.put(75, 0);
            numMap.put(76, 0);
            userSearch = userSearch + ".status";
        }else if (normalUser.getUserType() == 2){
            statuses = "79,81,83,85,86,87,95";
            numMap.put(79, 0);
            numMap.put(81, 0);
            numMap.put(83, 0);
            numMap.put(85, 0);
            numMap.put(86, 0);
            numMap.put(87, 0);
            numMap.put(95, 0);
        }
        Integer showUserId = userId;
        List<String> statusList = new ArrayList();
        if(StringUtil.isNotBlank(statuses)){
            String[] split = statuses.split(",");
            for (int i=0;i<split.length;i++){
                statusList.add(split[i]);
            }
        }
        for (String s : statusList){
            List sList = new ArrayList();
            sList.add(s);
            List<ManagerOrderDTO> dtos = orderMapper.selectAppOrderList(showUserId,normalUser.getUserType(),null,null,null,
                    null,null, null,null,
                    null, null,
                    sList, userSearch);
            numMap.put(Integer.valueOf(s), dtos.size());
        }
        APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
        ResultMessage resultMessage = ResultMessage.builder().setData(numMap);
        successMessage.setResult(resultMessage);
        return successMessage;
    }

    public APPResultMessage doReSettingOrder(int userId, Integer orderId) {

        MjOrder order = orderMapper.selectByPrimaryKey(orderId);
        //项目状态改为 核价中-未分配给渠道
        projectMapper.updateStatusById(order.getProjectId(), (short) 2);
        userOrderMapper.updateStatusByOrderIdAndUserIdAndOrderType(orderId, (short) 1, null, (short) 9);
        //开拓者状态为新订单
        //转移前的开拓者为新订单，未转移
        if (StringUtil.isNotBlank(order.getPushUserIds())){
            for (String pushUserId : order.getPushUserIds().split(",")) {
                MjUserOrderStatus mjUserOrderStatus = new MjUserOrderStatus();
                mjUserOrderStatus.setOrderStatus(79);
                mjUserOrderStatus.setUpdateTime(new Date());
                mjUserOrderStatus.setIsNextPush((short) 1);
                MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(Integer.valueOf(pushUserId), orderId);
                if (isHaveObj != null){
                    mjUserOrderStatus.setId(isHaveObj.getId());
                    mjUserOrderStatusMapper.updateByPrimaryKeySelective(mjUserOrderStatus);
                }
            }
        }
        //转移后的开拓者直接删除
        Set<String> uniqueSet = null;
        String[] arr1 = null;
        if (StringUtil.isNotBlank(order.getNextPushUserIds())){
            arr1 = order.getNextPushUserIds().trim().split(",");
        }
        String[] arr2 = null;
        if (StringUtil.isNotBlank(order.getTransferUserIds())){
            arr2 = order.getTransferUserIds().trim().split(",");
        }
        if (arr1 != null && arr2 != null){
            // 步骤2：合并数组
            String[] combined = Stream.concat(Arrays.stream(arr1), Arrays.stream(arr2))
                    .toArray(String[]::new);
            // 步骤3：去重
            uniqueSet = new HashSet<>(Arrays.asList(combined));
        }
        if (uniqueSet != null){
            for (String pushUserId : uniqueSet) {
                MjUserOrderStatus mjUserOrderStatus = new MjUserOrderStatus();
                mjUserOrderStatus.setStatus((short) 2);
                mjUserOrderStatus.setUpdateTime(new Date());
                MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(Integer.valueOf(pushUserId), orderId);
                if (isHaveObj != null){
                    mjUserOrderStatus.setId(isHaveObj.getId());
                    mjUserOrderStatusMapper.updateByPrimaryKeySelective(mjUserOrderStatus);
                }
            }
        }
        //渠道状态直接删除
        if (StringUtil.isNotBlank(order.getPushChannelUserIds())){
            for (String userIds : order.getPushChannelUserIds().split(",")) {
                if (StringUtil.isNotBlank(userIds)){
                    MjUserOrderStatus mjUserOrderStatus = new MjUserOrderStatus();
                    mjUserOrderStatus.setStatus((short) 2);
                    mjUserOrderStatus.setUpdateTime(new Date());
                    MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(Integer.valueOf(userIds), orderId);
                    if (isHaveObj != null){
                        mjUserOrderStatus.setId(isHaveObj.getId());
                        mjUserOrderStatusMapper.updateByPrimaryKeySelective(mjUserOrderStatus);
                    }
                }
            }
        }
        orderMapper.updateResettingOrder(orderId);
        orderMapper.updateReset(orderId);
        //记录操作日志
        logOperateMapper.addSelective(order.getProjectId(), order.getId(), userId,203,new Date(),1);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage doReSettingOrderTime(int userId, Integer orderId) {
        orderMapper.updateResettingOrderTime(orderId);
//        MjOrder order = orderMapper.selectByPrimaryKey(orderId);
//        projectMapper.updateStatusById(order.getProjectId(), (short) 4);
        userOrderMapper.updateStatusByOrderIdAndUserIdAndOrderType(orderId, (short) 2, null, (short) 9);
        userOrderMapper.updateStatusByOrderIdAndUserIdAndOrderType(orderId, (short) 3, null, (short) 9);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage abandonOrder(int userId, OrderIdReq req, Short userType) {
        MjOrder order = orderMapper.selectByPrimaryKey(req.getOrderId());
        if (userType == 1){
            MjNormalUser mjNormalUser = normalUserMapper.selectByPrimaryKey(order.getLastUserId());
            Integer pushUserId = mjNormalUser.getPushUserId();
            MjNormalUser user2 = normalUserMapper.selectByPrimaryKey(userId);
            if (user2.getIsAssistant() == 1) {
                if (userId != pushUserId){
                    return APPResultMessage.getErrorMessage("该开拓者暂无放弃订单的权限");
                }
            }else {
                if (user2.getAssistantUserIds().indexOf(pushUserId.toString()) == -1){
                    return APPResultMessage.getErrorMessage("该助理暂无放弃订单的权限");
                }
            }
            userId = order.getLastUserId();
        }
        if (order.getLastUserId() == userId){
            //找出二次竞价中没有放弃的列表
            List<MjUserOrder> userOrderList = userOrderMapper.selectNoAbandonList(req.getOrderId(), (short) 3);
            if (userOrderList != null && userOrderList.size()>0){
                //先修改已放弃
                //不限定type,把两次竞价都改为已放弃
                userOrderMapper.updateAbandonByOrderIdAndUserIdAndOrderType(req.getOrderId(),userId, (short) 2);
                //修改渠道状态为已结束
                mjUserOrderStatusMapper.updateOrderStatusByOrderIdAndUserId(req.getOrderId(), userId,78);
                //修改开拓者状态为已结束
                MjNormalUser mjNormalUser = normalUserMapper.selectByPrimaryKey(userId);
                mjUserOrderStatusMapper.updateOrderStatusByOrderIdAndUserId(req.getOrderId(), mjNormalUser.getPushUserId(),88);
                //判断是否有下一个
                Integer num = userOrderMapper.selectNumByOrderIdAndOrderType(req.getOrderId(), (short) 3);
                MjUserOrder mjUserOrder = userOrderMapper.selectIsHaveByOrderIdAndUserIdAndOrderType(userId, req.getOrderId(), (short) 3);
                if (mjUserOrder.getRankNum() == num){
                    //如果为最后一个，去一次竞价列表中寻找,找到倒序价格第一并且没有放弃过的的渠道
                    MjUserOrder isHasNextObj = userOrderMapper.selectNoAbandonNextUser(req.getOrderId());
                    if (isHasNextObj != null){
                        //如果一次竞价中有下一位
                        //修改下一名次为已中标
                        mjUserOrderStatusMapper.updateOrderStatusByOrderIdAndUserId(req.getOrderId(), isHasNextObj.getUserId(),93);
                        //开拓者为已拿下
                        MjNormalUser normalUser = normalUserMapper.selectByPrimaryKey(isHasNextObj.getUserId());
                        mjUserOrderStatusMapper.updateOrderStatusByOrderIdAndUserId(req.getOrderId(), normalUser.getPushUserId(),99);
                        //修改order表的last和topprice
                        MjOrder order1 = new MjOrder();
                        order1.setId(req.getOrderId());
                        order1.setLastUserId(isHasNextObj.getUserId());
                        //一次竞价最高价
                        order1.setBiddingOneFirstPrice(isHasNextObj.getTotalPrice());
                        orderMapper.updateByPrimaryKeySelective(order1);
                        //清空二次竞价最高价
                        orderMapper.clearSecondBiddingPrice(req.getOrderId());
                    } else {
                        //如果一次竞价中也没有下一位
                        //订单为已流单
                        orderMapper.updateStatusByOrderId(req.getOrderId(),(short) 11);
                        //清空order表的lastUserId和一次竞价最高价
                        orderMapper.updateLastUserId(req.getOrderId());
                    }
                } else {
                    //如果不是二次竞价中最后一个
                    //修改下一名次为已中标，开拓者为已拿下
                    MjUserOrder nextUserOrder = userOrderMapper.selectUserByOrderIdAndOrderTypeAndRankNum(req.getOrderId(), (short) 3, mjUserOrder.getRankNum() + 1);
                    MjNormalUser nextUser = normalUserMapper.selectByPrimaryKey(nextUserOrder.getUserId());
                    mjUserOrderStatusMapper.updateOrderStatusByOrderIdAndUserId(req.getOrderId(), nextUserOrder.getUserId(),93);
                    mjUserOrderStatusMapper.updateOrderStatusByOrderIdAndUserId(req.getOrderId(), nextUser.getPushUserId(),99);
                    //修改order表的last和topprice
                    MjOrder order1 = new MjOrder();
                    order1.setId(req.getOrderId());
                    order1.setLastUserId(nextUserOrder.getUserId());
                    order1.setBiddingTwoTopPrice(nextUserOrder.getTotalPrice());
                    orderMapper.updateByPrimaryKeySelective(order1);
                }
            } else {
                //如果二次竞价没有未放弃的渠道，则直接进入一次竞价列表
                //不限定type,把两次竞价都改为已放弃
                userOrderMapper.updateAbandonByOrderIdAndUserIdAndOrderType(req.getOrderId(), userId, (short) 2);
                //修改渠道状态为已结束
                mjUserOrderStatusMapper.updateOrderStatusByOrderIdAndUserId(req.getOrderId(), userId,78);
                //修改开拓者状态为已结束
                MjNormalUser mjNormalUser = normalUserMapper.selectByPrimaryKey(userId);
                mjUserOrderStatusMapper.updateOrderStatusByOrderIdAndUserId(req.getOrderId(), mjNormalUser.getPushUserId(),88);
                //判断是否有下一个没有放弃的渠道
                MjUserOrder isHasNextObj = userOrderMapper.selectNoAbandonNextUser(req.getOrderId());
                if (isHasNextObj != null){
                    //如果有下一个
                    //修改下一名次为已中标
                    mjUserOrderStatusMapper.updateOrderStatusByOrderIdAndUserId(req.getOrderId(), isHasNextObj.getUserId(),93);
                    //开拓者为已拿下
                    MjNormalUser normalUser = normalUserMapper.selectByPrimaryKey(isHasNextObj.getUserId());
                    mjUserOrderStatusMapper.updateOrderStatusByOrderIdAndUserId(req.getOrderId(), normalUser.getPushUserId(),99);
                    //修改order表的last和topprice
                    MjOrder order1 = new MjOrder();
                    order1.setId(req.getOrderId());
                    order1.setLastUserId(isHasNextObj.getUserId());
                    //一次竞价最高价
                    order1.setBiddingOneFirstPrice(isHasNextObj.getTotalPrice());
                    orderMapper.updateByPrimaryKeySelective(order1);
                } else {
                    //如果没有下一个
                    //订单为已流单
                    orderMapper.updateStatusByOrderId(req.getOrderId(),(short) 11);
                    //清空order表的lastUserId和一次竞价最高价
                    orderMapper.updateLastUserId(req.getOrderId());
                }
            }
        }
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage replyTimeOutRemark(Integer userId, Integer orderId, String content) {
        MjUserOrderStatus isHaveObj2 = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(userId, orderId);
        if (isHaveObj2 != null && isHaveObj2.getOrderStatus() == 95){
            MjOrder order = orderMapper.selectByPrimaryKey(orderId);
            Set<Integer> allPushUserIds = getAllPushUserIds(order.getPushUserIds(), order.getNextPushUserIds(), order.getTransferUserIds(),order.getBiddingPushUserIds());
            MjOrderTimeOutRemark orderTimeOutRemark = new MjOrderTimeOutRemark();
            orderTimeOutRemark.setOrderId(orderId);
            orderTimeOutRemark.setUserId(userId);
            orderTimeOutRemark.setContent(content);
            orderTimeOutRemark.setContentType((short) 2);
            orderTimeOutRemark.setCreateTime(new Date());
            orderTimeOutRemark.setStatus(1);
            //新增记录
            orderTimeOutRemarkMapper.insertSelective(orderTimeOutRemark);
            //开拓者/助理进行反馈
            //订单状态改为商务提交说明之前的状态
            for (Integer pushUserId : allPushUserIds) {
                MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(pushUserId, orderId);
                if (isHaveObj != null){
                    MjUserOrderStatus mjUserOrderStatus = new MjUserOrderStatus();
                    mjUserOrderStatus.setId(isHaveObj.getId());
                    mjUserOrderStatus.setOrderStatus(isHaveObj.getPreviousStatus());
                    mjUserOrderStatus.setUpdateTime(new Date());
                    mjUserOrderStatusMapper.updateByPrimaryKeySelective(mjUserOrderStatus);
                }
            }
            orderMapper.updateIsTimeOut(orderId, (short) 1);
            return APPResultMessage.getSuccessMessage();
        } else {
            return APPResultMessage.getErrorMessage("暂无商务反馈");
        }


    }


    public  void moveStatus(MjOrder order, Integer parentOrderId, List<Integer> userIdList) {
        List<Integer> orderIdList = orderMapper.selectOtherIdList(order.getId(), parentOrderId);
        if (CollUtil.isNotEmpty(orderIdList)){
            for (Integer orderId : orderIdList) {
                if (StrUtil.isNotBlank(order.getPushUserIds())){
                   Integer originId = Integer.valueOf(order.getPushUserIds().split(",")[0]);
                   //拿到原开拓者的订单状态信息
                    MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(originId, orderId);
                    if (ObjUtil.isNotNull(isHaveObj)){
                        for (Integer userId : userIdList) {
                            //其他开拓者
                            if (!order.getPushUserIds().contains(String.valueOf(userId))){
                                //判断其他开拓者对该订单有没有状态
                                MjUserOrderStatus isHaveObj2 = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(userId, orderId);
                                if (ObjUtil.isNotNull(isHaveObj2)){
                                    isHaveObj2.setOrderStatus(isHaveObj.getOrderStatus());
                                    isHaveObj2.setUpdateTime(new Date());
                                    mjUserOrderStatusMapper.updateByPrimaryKeySelective(isHaveObj2);
                                } else {
                                    MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                                    orderStatusObj.setUserId(userId);
                                    orderStatusObj.setOrderId(orderId);
                                    orderStatusObj.setOrderStatus(isHaveObj.getOrderStatus());
                                    orderStatusObj.setCreateTime(new Date());
                                    orderStatusObj.setStatus((short)1);
                                    orderStatusObj.setIsNextPush((short)1);
                                    mjUserOrderStatusMapper.insertSelective(orderStatusObj);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    public APPResultMessage doSetAppOrderRate(int userId, Integer orderId, Integer rateId) {
        String key = "doSetOrderRate_" + orderId;
        String requestId = UUID.randomUUID().toString();
        boolean flag = LockUtil.tryGetDistributedLock(key, requestId);
        if (flag){
            MjOrderOtherSetting otherSetting = orderOtherSettingMapper.selectMsgByOrderId(orderId);
            if (otherSetting == null){
                MjOrderOtherSetting setting = new MjOrderOtherSetting();
                setting.setOrderId(orderId);
                setting.setRateId(rateId);
                orderOtherSettingMapper.insertSelective(setting);
            }else {
                orderOtherSettingMapper.updateRateByOrderId(orderId, rateId);
            }
            // 添加修改记录
            MjOrderRateRecord record = new MjOrderRateRecord();
            record.setOrderId(orderId);
            record.setUserType((short) 1);
            record.setUserId(userId);
            record.setRateId(rateId);
            record.setCreateTime(new Date());
            orderRateRecordMapper.insertSelective(record);
            LockUtil.releaseDistributedLock(key, requestId);
            return APPResultMessage.getSuccessMessage();
        }else {
            return APPResultMessage.getErrorMessage("有账户在提交评级，请稍后重新提交");
        }
    }
}
